diff --git a/Wallet/Sources/AppDelegate.swift b/Wallet/Sources/AppDelegate.swift index 4ad5ae4f524..bc7f4963c27 100644 --- a/Wallet/Sources/AppDelegate.swift +++ b/Wallet/Sources/AppDelegate.swift @@ -757,15 +757,28 @@ final class AppDelegate: NSObject, UIApplicationDelegate { |> deliverOnMainQueue).start(next: { records, publicKey in if let record = records.first { if let publicKey = publicKey { - if record.info.encryptedSecret.publicKey == publicKey { - if record.exportCompleted { - let _ = (walletAddress(publicKey: record.info.publicKey, tonInstance: walletContext.tonInstance) - |> deliverOnMainQueue).start(next: { address in - let infoScreen = WalletInfoScreen(context: walletContext, walletInfo: record.info, address: address, enableDebugActions: false) - beginWithController(infoScreen) - }) - } else { - let createdScreen = WalletSplashScreen(context: walletContext, mode: .created(walletInfo: record.info, words: nil), walletCreatedPreloadState: nil) + let recordPublicKey: Data + switch record.info { + case let .ready(info, _, _): + recordPublicKey = info.encryptedSecret.publicKey + case let .imported(info): + recordPublicKey = info.encryptedSecret.publicKey + } + if recordPublicKey == publicKey { + switch record.info { + case let .ready(info, exportCompleted, _): + if exportCompleted { + let _ = (walletAddress(walletInfo: info, tonInstance: walletContext.tonInstance) + |> deliverOnMainQueue).start(next: { address in + let infoScreen = WalletInfoScreen(context: walletContext, walletInfo: info, address: address, enableDebugActions: false) + beginWithController(infoScreen) + }) + } else { + let createdScreen = WalletSplashScreen(context: walletContext, mode: .created(walletInfo: info, words: nil), walletCreatedPreloadState: nil) + beginWithController(createdScreen) + } + case let .imported(info): + let createdScreen = WalletSplashScreen(context: walletContext, mode: .successfullyImported(importedInfo: info), walletCreatedPreloadState: nil) beginWithController(createdScreen) } } else { diff --git a/submodules/PeerInfoUI/Sources/ChannelAdminController.swift b/submodules/PeerInfoUI/Sources/ChannelAdminController.swift index f26291b8a4e..d2544ac4d50 100644 --- a/submodules/PeerInfoUI/Sources/ChannelAdminController.swift +++ b/submodules/PeerInfoUI/Sources/ChannelAdminController.swift @@ -1004,6 +1004,8 @@ public func channelAdminController(context: AccountContext, peerId: PeerId, admi if let peer = adminView.peers[adminView.peerId] { text = presentationData.strings.Privacy_GroupsAndChannels_InviteToGroupError(peer.compactDisplayTitle, peer.compactDisplayTitle).0 } + case .notMutualContact: + text = presentationData.strings.GroupInfo_AddUserLeftError default: break } diff --git a/submodules/PeerInfoUI/Sources/ChannelMembersController.swift b/submodules/PeerInfoUI/Sources/ChannelMembersController.swift index 91978d4998d..fcad5942b59 100644 --- a/submodules/PeerInfoUI/Sources/ChannelMembersController.swift +++ b/submodules/PeerInfoUI/Sources/ChannelMembersController.swift @@ -396,6 +396,8 @@ public func channelMembersController(context: AccountContext, peerId: PeerId) -> text = presentationData.strings.Login_UnknownError case .restricted: text = presentationData.strings.Channel_ErrorAddBlocked + case .notMutualContact: + text = presentationData.strings.GroupInfo_AddUserLeftError case let .bot(memberId): let _ = (context.account.postbox.transaction { transaction in return transaction.getPeer(peerId) diff --git a/submodules/PeerInfoUI/Sources/GroupInfoController.swift b/submodules/PeerInfoUI/Sources/GroupInfoController.swift index 9578132a8fc..4ee98d59643 100644 --- a/submodules/PeerInfoUI/Sources/GroupInfoController.swift +++ b/submodules/PeerInfoUI/Sources/GroupInfoController.swift @@ -1750,7 +1750,7 @@ public func groupInfoController(context: AccountContext, peerId originalPeerId: return state.withUpdatedTemporaryParticipants(temporaryParticipants).withUpdatedSuccessfullyAddedParticipantIds(successfullyAddedParticipantIds) } return .complete() - case .privacy: + case .privacy, .notMutualContact: let _ = (context.account.postbox.loadedPeerWithId(memberId) |> deliverOnMainQueue).start(next: { peer in presentControllerImpl?(textAlertController(context: context, title: nil, text: presentationData.strings.Privacy_GroupsAndChannels_InviteToGroupError(peer.compactDisplayTitle, peer.compactDisplayTitle).0, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: {})]), nil) diff --git a/submodules/TelegramCore/Sources/AddPeerMember.swift b/submodules/TelegramCore/Sources/AddPeerMember.swift index 4bc8e65ca07..5edaa1c5535 100644 --- a/submodules/TelegramCore/Sources/AddPeerMember.swift +++ b/submodules/TelegramCore/Sources/AddPeerMember.swift @@ -10,6 +10,7 @@ public enum AddGroupMemberError { case generic case groupFull case privacy + case notMutualContact case tooManyChannels } @@ -26,6 +27,8 @@ public func addGroupMember(account: Account, peerId: PeerId, memberId: PeerId) - return .privacy case "USER_CHANNELS_TOO_MUCH": return .tooManyChannels + case "USER_NOT_MUTUAL_CONTACT": + return .notMutualContact default: return .generic } @@ -68,6 +71,7 @@ public func addGroupMember(account: Account, peerId: PeerId, memberId: PeerId) - public enum AddChannelMemberError { case generic case restricted + case notMutualContact case limitExceeded case tooMuchJoined case bot(PeerId) @@ -98,8 +102,10 @@ public func addChannelMember(account: Account, peerId: PeerId, memberId: PeerId) return .fail(.tooMuchJoined) case "USERS_TOO_MUCH": return .fail(.limitExceeded) - case "USER_PRIVACY_RESTRICTED", "USER_NOT_MUTUAL_CONTACT": + case "USER_PRIVACY_RESTRICTED": return .fail(.restricted) + case "USER_NOT_MUTUAL_CONTACT": + return .fail(.notMutualContact) case "USER_BOT": return .fail(.bot(memberId)) case "BOT_GROUPS_BLOCKED": @@ -194,8 +200,10 @@ public func addChannelMembers(account: Account, peerId: PeerId, memberIds: [Peer switch error.errorDescription { case "CHANNELS_TOO_MUCH": return .tooMuchJoined - case "USER_PRIVACY_RESTRICTED", "USER_NOT_MUTUAL_CONTACT": + case "USER_PRIVACY_RESTRICTED": return .restricted + case "USER_NOT_MUTUAL_CONTACT": + return .notMutualContact case "USERS_TOO_MUCH": return .limitExceeded default: diff --git a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoScreen.swift b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoScreen.swift index 9cb61506e42..7a54aacfe23 100644 --- a/submodules/TelegramUI/Sources/PeerInfo/PeerInfoScreen.swift +++ b/submodules/TelegramUI/Sources/PeerInfo/PeerInfoScreen.swift @@ -3342,6 +3342,12 @@ private final class PeerInfoScreenNode: ViewControllerTracingNode, UIScrollViewD self?.controller?.present(textAlertController(context: context, title: nil, text: presentationData.strings.Privacy_GroupsAndChannels_InviteToGroupError(peer.compactDisplayTitle, peer.compactDisplayTitle).0, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: {})]), in: .window(.root)) }) return .complete() + case .notMutualContact: + let _ = (context.account.postbox.loadedPeerWithId(memberId) + |> deliverOnMainQueue).start(next: { peer in + self?.controller?.present(textAlertController(context: context, title: nil, text: presentationData.strings.GroupInfo_AddUserLeftError, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: {})]), in: .window(.root)) + }) + return .complete() case .tooManyChannels: let _ = (context.account.postbox.loadedPeerWithId(memberId) |> deliverOnMainQueue).start(next: { peer in @@ -3399,7 +3405,7 @@ private final class PeerInfoScreenNode: ViewControllerTracingNode, UIScrollViewD return context.account.postbox.multiplePeersView(memberIds) |> take(1) |> deliverOnMainQueue - |> castError(AddChannelMemberError.self) + |> castError(AddChannelMemberError.self) |> mapToSignal { view -> Signal in if memberIds.count == 1 { return context.peerChannelMemberCategoriesContextsManager.addMember(account: context.account, peerId: groupPeer.id, memberId: memberIds[0]) @@ -3479,6 +3485,8 @@ private final class PeerInfoScreenNode: ViewControllerTracingNode, UIScrollViewD default: break } + } else if peers.count == 1, case .notMutualContact = error { + self?.controller?.present(textAlertController(context: context, title: nil, text: presentationData.strings.GroupInfo_AddUserLeftError, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: {})]), in: .window(.root)) } else if case .tooMuchJoined = error { self?.controller?.present(textAlertController(context: context, title: nil, text: presentationData.strings.Invite_ChannelsTooMuch, actions: [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_OK, action: {})]), in: .window(.root)) } diff --git a/submodules/TonBinding/Sources/TON.h b/submodules/TonBinding/Sources/TON.h index 5e95749e2a5..31c0dc812f3 100644 --- a/submodules/TonBinding/Sources/TON.h +++ b/submodules/TonBinding/Sources/TON.h @@ -30,12 +30,15 @@ NS_ASSUME_NONNULL_BEGIN @interface TONAccountState : NSObject @property (nonatomic, readonly) bool isInitialized; +@property (nonatomic, readonly) bool isRWallet; @property (nonatomic, readonly) int64_t balance; +@property (nonatomic, readonly) int64_t unlockedBalance; + @property (nonatomic, readonly) int32_t seqno; @property (nonatomic, strong, readonly) TONTransactionId * _Nullable lastTransactionId; @property (nonatomic, readonly) int64_t syncUtime; -- (instancetype)initWithIsInitialized:(bool)isInitialized balance:(int64_t)balance seqno:(int32_t)seqno lastTransactionId:(TONTransactionId * _Nullable)lastTransactionId syncUtime:(int64_t)syncUtime; +- (instancetype)initWithIsInitialized:(bool)isInitialized isRWallet:(bool)isRWallet balance:(int64_t)balance unlockedBalance:(int64_t)unlockedBalance seqno:(int32_t)seqno lastTransactionId:(TONTransactionId * _Nullable)lastTransactionId syncUtime:(int64_t)syncUtime; @end @@ -166,7 +169,7 @@ NS_ASSUME_NONNULL_BEGIN - (SSignal *)validateConfig:(NSString *)config blockchainName:(NSString *)blockchainName; - (SSignal *)createKeyWithLocalPassword:(NSData *)localPassword mnemonicPassword:(NSData *)mnemonicPassword; -- (SSignal *)getWalletAccountAddressWithPublicKey:(NSString *)publicKey initialWalletId:(int64_t)initialWalletId; +- (SSignal *)getWalletAccountAddressWithPublicKey:(NSString *)publicKey initialWalletId:(int64_t)initialWalletId rwalletInitialPublicKey:(NSString * _Nullable)rwalletInitialPublicKey; - (SSignal *)getAccountStateWithAddress:(NSString *)accountAddress; - (SSignal *)generateSendGramsQueryFromKey:(TONKey *)key localPassword:(NSData *)localPassword fromAddress:(NSString *)fromAddress toAddress:(NSString *)address amount:(int64_t)amount comment:(NSData *)comment encryptComment:(bool)encryptComment forceIfDestinationNotInitialized:(bool)forceIfDestinationNotInitialized timeout:(int32_t)timeout randomId:(int64_t)randomId; - (SSignal *)generateFakeSendGramsQueryFromAddress:(NSString *)fromAddress toAddress:(NSString *)address amount:(int64_t)amount comment:(NSData *)comment encryptComment:(bool)encryptComment forceIfDestinationNotInitialized:(bool)forceIfDestinationNotInitialized timeout:(int32_t)timeout; diff --git a/submodules/TonBinding/Sources/TON.mm b/submodules/TonBinding/Sources/TON.mm index 99c53cbbdac..1ff7dc656d4 100644 --- a/submodules/TonBinding/Sources/TON.mm +++ b/submodules/TonBinding/Sources/TON.mm @@ -98,11 +98,13 @@ - (instancetype)initWithPublicKey:(NSString *)publicKey secret:(NSData *)secret @implementation TONAccountState -- (instancetype)initWithIsInitialized:(bool)isInitialized balance:(int64_t)balance seqno:(int32_t)seqno lastTransactionId:(TONTransactionId * _Nullable)lastTransactionId syncUtime:(int64_t)syncUtime { +- (instancetype)initWithIsInitialized:(bool)isInitialized isRWallet:(bool)isRWallet balance:(int64_t)balance unlockedBalance:(int64_t)unlockedBalance seqno:(int32_t)seqno lastTransactionId:(TONTransactionId * _Nullable)lastTransactionId syncUtime:(int64_t)syncUtime { self = [super init]; if (self != nil) { _isInitialized = isInitialized; + _isRWallet = isRWallet; _balance = balance; + _unlockedBalance = unlockedBalance; _seqno = seqno; _lastTransactionId = lastTransactionId; _syncUtime = syncUtime; @@ -632,7 +634,7 @@ - (SSignal *)createKeyWithLocalPassword:(NSData *)localPassword mnemonicPassword }] startOn:[SQueue mainQueue]] deliverOn:[SQueue mainQueue]]; } -- (SSignal *)getWalletAccountAddressWithPublicKey:(NSString *)publicKey initialWalletId:(int64_t)initialWalletId { +- (SSignal *)getWalletAccountAddressWithPublicKey:(NSString *)publicKey initialWalletId:(int64_t)initialWalletId rwalletInitialPublicKey:(NSString * _Nullable)rwalletInitialPublicKey { return [[[[SSignal alloc] initWithGenerator:^id(SSubscriber *subscriber) { NSData *publicKeyData = [publicKey dataUsingEncoding:NSUTF8StringEncoding]; if (publicKeyData == nil) { @@ -640,6 +642,15 @@ - (SSignal *)getWalletAccountAddressWithPublicKey:(NSString *)publicKey initialW return [[SBlockDisposable alloc] initWithBlock:^{}]; } + NSData *rwalletInitialPublicKeyData = nil; + if (rwalletInitialPublicKey != nil) { + rwalletInitialPublicKeyData = [rwalletInitialPublicKey dataUsingEncoding:NSUTF8StringEncoding]; + if (rwalletInitialPublicKeyData == nil) { + [subscriber putError:[[TONError alloc] initWithText:@"Error encoding UTF8 string for rwalletInitialPublicKey in getWalletAccountAddressWithPublicKey"]]; + return [[SBlockDisposable alloc] initWithBlock:^{}]; + } + } + uint64_t requestId = _nextRequestId; _nextRequestId += 1; @@ -656,14 +667,27 @@ - (SSignal *)getWalletAccountAddressWithPublicKey:(NSString *)publicKey initialW } }]; - auto initialAccountState = make_object( - makeString(publicKeyData), - initialWalletId - ); + tonlib_api::object_ptr initialAccountState; + + std::int32_t revision; + if (rwalletInitialPublicKey != nil) { + initialAccountState = make_object( + makeString(rwalletInitialPublicKeyData), + makeString(publicKeyData), + initialWalletId + ); + revision = -1; + } else { + initialAccountState = tonlib_api::move_object_as(make_object( + makeString(publicKeyData), + initialWalletId + )); + revision = 1; + } auto query = make_object( tonlib_api::move_object_as(initialAccountState), - 1 + revision ); _client->send({ requestId, std::move(query) }); @@ -684,12 +708,21 @@ - (SSignal *)getAccountStateWithAddress:(NSString *)accountAddress { } else if (object->get_id() == tonlib_api::fullAccountState::ID) { auto fullAccountState = tonlib_api::move_object_as(object); int32_t seqNo = -1; + + bool isRWallet = false; + int64_t unlockedBalance = INT64_MAX; + if (fullAccountState->account_state_->get_id() == tonlib_api::uninited_accountState::ID) { seqNo = -1; } else if (fullAccountState->account_state_->get_id() == tonlib_api::wallet_v3_accountState::ID) { auto v3AccountState = tonlib_api::move_object_as(fullAccountState->account_state_); seqNo = v3AccountState->seqno_; - } else { + } else if (fullAccountState->account_state_->get_id() == tonlib_api::rwallet_accountState::ID) { + auto rwalletAccountState = tonlib_api::move_object_as(fullAccountState->account_state_); + isRWallet = true; + unlockedBalance = rwalletAccountState->unlocked_balance_; + seqNo = rwalletAccountState->seqno_; + }else { [subscriber putError:[[TONError alloc] initWithText:@"Unknown type"]]; return; } @@ -698,7 +731,7 @@ - (SSignal *)getAccountStateWithAddress:(NSString *)accountAddress { if (fullAccountState->last_transaction_id_ != nullptr) { lastTransactionId = [[TONTransactionId alloc] initWithLt:fullAccountState->last_transaction_id_->lt_ transactionHash:makeData(fullAccountState->last_transaction_id_->hash_)]; } - [subscriber putNext:[[TONAccountState alloc] initWithIsInitialized:false balance:fullAccountState->balance_ seqno:-1 lastTransactionId:lastTransactionId syncUtime:fullAccountState->sync_utime_]]; + [subscriber putNext:[[TONAccountState alloc] initWithIsInitialized:false isRWallet:isRWallet balance:fullAccountState->balance_ unlockedBalance:unlockedBalance seqno:-1 lastTransactionId:lastTransactionId syncUtime:fullAccountState->sync_utime_]]; [subscriber putCompletion]; } else { assert(false); @@ -785,7 +818,8 @@ - (SSignal *)generateSendGramsQueryFromKey:(TONKey *)key localPassword:(NSData * ), make_object(fromAddress.UTF8String), timeout, - tonlib_api::move_object_as(inputAction) + tonlib_api::move_object_as(inputAction), + nil ); _client->send({ requestId, std::move(query) }); @@ -840,7 +874,8 @@ - (SSignal *)generateFakeSendGramsQueryFromAddress:(NSString *)fromAddress toAdd make_object(), make_object(fromAddress.UTF8String), timeout, - tonlib_api::move_object_as(inputAction) + tonlib_api::move_object_as(inputAction), + nil ); _client->send({ requestId, std::move(query) }); diff --git a/submodules/WalletCore/Sources/WalletCore.swift b/submodules/WalletCore/Sources/WalletCore.swift index 1b1edce4eb4..d233a4ba431 100644 --- a/submodules/WalletCore/Sources/WalletCore.swift +++ b/submodules/WalletCore/Sources/WalletCore.swift @@ -198,7 +198,7 @@ public final class TonInstance { } let _ = keychain.encrypt(key.secret).start(next: { encryptedSecretData in let _ = self.exportKey(key: key, localPassword: localPassword).start(next: { wordList in - subscriber.putNext((WalletInfo(publicKey: WalletPublicKey(rawValue: key.publicKey), encryptedSecret: encryptedSecretData), wordList)) + subscriber.putNext((WalletInfo(publicKey: WalletPublicKey(rawValue: key.publicKey), rWalletInitialPublicKey: nil, encryptedSecret: encryptedSecretData), wordList)) subscriber.putCompletion() }, error: { error in subscriber.putError(.generic) @@ -220,7 +220,7 @@ public final class TonInstance { } } - fileprivate func importWallet(keychain: TonKeychain, wordList: [String], localPassword: Data) -> Signal { + fileprivate func importWallet(keychain: TonKeychain, wordList: [String], localPassword: Data) -> Signal { return Signal { subscriber in let disposable = MetaDisposable() @@ -232,7 +232,7 @@ public final class TonInstance { return } let _ = keychain.encrypt(key.secret).start(next: { encryptedSecretData in - subscriber.putNext(WalletInfo(publicKey: WalletPublicKey(rawValue: key.publicKey), encryptedSecret: encryptedSecretData)) + subscriber.putNext(ImportedWalletInfo(publicKey: WalletPublicKey(rawValue: key.publicKey), encryptedSecret: encryptedSecretData)) subscriber.putCompletion() }, error: { _ in subscriber.putError(.generic) @@ -283,7 +283,7 @@ public final class TonInstance { } } - fileprivate func walletAddress(publicKey: WalletPublicKey) -> Signal { + fileprivate func walletAddress(publicKey: WalletPublicKey, rwalletInitialPublicKey: WalletInitialPublicKey?) -> Signal { return self.getInitialWalletId() |> `catch` { _ -> Signal in return .single(0) @@ -294,7 +294,7 @@ public final class TonInstance { self.impl.with { impl in impl.withInstance { ton in - let cancel = ton.getWalletAccountAddress(withPublicKey: publicKey.rawValue, initialWalletId: initialWalletId).start(next: { address in + let cancel = ton.getWalletAccountAddress(withPublicKey: publicKey.rawValue, initialWalletId: initialWalletId, rwalletInitialPublicKey: rwalletInitialPublicKey?.rawValue).start(next: { address in guard let address = address as? String else { return } @@ -353,7 +353,7 @@ public final class TonInstance { fileprivate func getWalletState(address: String) -> Signal<(WalletState, Int64), GetWalletStateError> { return self.getWalletStateRaw(address: address) |> map { state in - return (WalletState(balance: state.balance, lastTransactionId: state.lastTransactionId.flatMap(WalletTransactionId.init(tonTransactionId:))), state.syncUtime) + return (WalletState(totalBalance: state.balance, unlockedBalance: state.isRWallet ? state.unlockedBalance : nil, lastTransactionId: state.lastTransactionId.flatMap(WalletTransactionId.init(tonTransactionId:))), state.syncUtime) } } @@ -717,7 +717,27 @@ public struct WalletPublicKey: Codable, Hashable { } } +public struct WalletInitialPublicKey: Codable, Hashable { + public var rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } +} + public struct WalletInfo: Codable, Equatable { + public let publicKey: WalletPublicKey + public let rWalletInitialPublicKey: WalletInitialPublicKey? + public let encryptedSecret: TonKeychainEncryptedData + + public init(publicKey: WalletPublicKey, rWalletInitialPublicKey: WalletInitialPublicKey?, encryptedSecret: TonKeychainEncryptedData) { + self.publicKey = publicKey + self.rWalletInitialPublicKey = rWalletInitialPublicKey + self.encryptedSecret = encryptedSecret + } +} + +public struct ImportedWalletInfo: Codable, Equatable { public let publicKey: WalletPublicKey public let encryptedSecret: TonKeychainEncryptedData @@ -743,15 +763,50 @@ public struct CombinedWalletState: Codable, Equatable { } } +public enum WalletStateRecordDecodingError: Error { + case generic +} + public struct WalletStateRecord: Codable, Equatable { - public let info: WalletInfo - public var exportCompleted: Bool - public var state: CombinedWalletState? + enum Key: CodingKey { + case info + case exportCompleted + case state + case importedInfo + } - public init(info: WalletInfo, exportCompleted: Bool, state: CombinedWalletState?) { + public enum Info: Equatable { + case ready(info: WalletInfo, exportCompleted: Bool, state: CombinedWalletState?) + case imported(info: ImportedWalletInfo) + } + + public var info: WalletStateRecord.Info + + public init(info: WalletStateRecord.Info) { self.info = info - self.exportCompleted = exportCompleted - self.state = state + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: Key.self) + if let info = try? container.decode(WalletInfo.self, forKey: .info) { + self.info = .ready(info: info, exportCompleted: (try? container.decode(Bool.self, forKey: .exportCompleted)) ?? false, state: try? container.decode(Optional.self, forKey: .state)) + } else if let info = try? container.decode(ImportedWalletInfo.self, forKey: .importedInfo) { + self.info = .imported(info: info) + } else { + throw WalletStateRecordDecodingError.generic + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: Key.self) + switch info { + case let .ready(info, exportCompleted, state): + try container.encode(info, forKey: .info) + try container.encode(exportCompleted, forKey: .exportCompleted) + try container.encode(state, forKey: .state) + case let .imported(info): + try container.encode(info, forKey: .importedInfo) + } } } @@ -771,7 +826,7 @@ public func createWallet(storage: WalletStorageInterface, tonInstance: TonInstan |> mapToSignal { walletInfo, wordList -> Signal<(WalletInfo, [String]), CreateWalletError> in return storage.updateWalletRecords({ records in var records = records - records.append(WalletStateRecord(info: walletInfo, exportCompleted: false, state: nil)) + records.append(WalletStateRecord(info: .ready(info: walletInfo, exportCompleted: false, state: nil))) return records }) |> map { _ -> (WalletInfo, [String]) in @@ -785,8 +840,13 @@ public func confirmWalletExported(storage: WalletStorageInterface, publicKey: Wa return storage.updateWalletRecords { records in var records = records for i in 0 ..< records.count { - if records[i].info.publicKey == publicKey { - records[i].exportCompleted = true + switch records[i].info { + case let .ready(info, _, state): + if info.publicKey == publicKey { + records[i].info = .ready(info: info, exportCompleted: true, state: state) + } + case .imported: + break } } return records @@ -802,21 +862,21 @@ public enum ImportWalletError { case generic } -public func importWallet(storage: WalletStorageInterface, tonInstance: TonInstance, keychain: TonKeychain, wordList: [String], localPassword: Data) -> Signal { +public func importWallet(storage: WalletStorageInterface, tonInstance: TonInstance, keychain: TonKeychain, wordList: [String], localPassword: Data) -> Signal { return tonInstance.importWallet(keychain: keychain, wordList: wordList, localPassword: localPassword) - |> `catch` { error -> Signal in + |> `catch` { error -> Signal in switch error { case .generic: return .fail(.generic) } } - |> mapToSignal { walletInfo -> Signal in + |> mapToSignal { walletInfo -> Signal in return storage.updateWalletRecords { records in var records = records - records.append(WalletStateRecord(info: walletInfo, exportCompleted: true, state: nil)) + records.append(WalletStateRecord(info: .imported(info: walletInfo))) return records } - |> map { _ -> WalletInfo in + |> map { _ -> ImportedWalletInfo in return walletInfo } |> castError(ImportWalletError.self) @@ -848,17 +908,29 @@ public func walletRestoreWords(tonInstance: TonInstance, publicKey: WalletPublic } public struct WalletState: Codable, Equatable { - public let balance: Int64 + public let totalBalance: Int64 + public let unlockedBalance: Int64? public let lastTransactionId: WalletTransactionId? - public init(balance: Int64, lastTransactionId: WalletTransactionId?) { - self.balance = balance + public init(totalBalance: Int64, unlockedBalance: Int64?, lastTransactionId: WalletTransactionId?) { + self.totalBalance = totalBalance + self.unlockedBalance = unlockedBalance self.lastTransactionId = lastTransactionId } } -public func walletAddress(publicKey: WalletPublicKey, tonInstance: TonInstance) -> Signal { - return tonInstance.walletAddress(publicKey: publicKey) +public extension WalletState { + var effectiveAvailableBalance: Int64 { + if let unlockedBalance = self.unlockedBalance { + return unlockedBalance + } else { + return self.totalBalance + } + } +} + +public func walletAddress(walletInfo: WalletInfo, tonInstance: TonInstance) -> Signal { + return tonInstance.walletAddress(publicKey: walletInfo.publicKey, rwalletInitialPublicKey: walletInfo.rWalletInitialPublicKey) } private enum GetWalletStateError { @@ -882,7 +954,39 @@ public enum CombinedWalletStateResult { public enum CombinedWalletStateSubject { case wallet(WalletInfo) - case address(String) +} + +public enum GetWalletInfoError { + case generic + case network +} + +public func getWalletInfo(importedInfo: ImportedWalletInfo, tonInstance: TonInstance) -> Signal { + let rwalletInitialPublicKey = WalletInitialPublicKey(rawValue: "Pua8zmvG8934jf2mAysxTMUJUaxoXQskZKfqsAoGUjS2Kj4J") + return tonInstance.walletAddress(publicKey: importedInfo.publicKey, rwalletInitialPublicKey: rwalletInitialPublicKey) + |> castError(GetWalletInfoError.self) + |> mapToSignal { address -> Signal in + return tonInstance.getWalletState(address: address) + |> mapError { error -> GetWalletInfoError in + switch error { + case .generic: + return .generic + case .network: + return .network + } + } + |> mapToSignal { state -> Signal in + if state.0.unlockedBalance != nil { + return .single(WalletInfo(publicKey: importedInfo.publicKey, rWalletInitialPublicKey: rwalletInitialPublicKey, encryptedSecret: importedInfo.encryptedSecret)) + } else { + return tonInstance.walletAddress(publicKey: importedInfo.publicKey, rwalletInitialPublicKey: nil) + |> castError(GetWalletInfoError.self) + |> map { address -> WalletInfo in + return WalletInfo(publicKey: importedInfo.publicKey, rWalletInitialPublicKey: nil, encryptedSecret: importedInfo.encryptedSecret) + } + } + } + } } public func getCombinedWalletState(storage: WalletStorageInterface, subject: CombinedWalletStateSubject, tonInstance: TonInstance, onlyCached: Bool) -> Signal { @@ -891,8 +995,13 @@ public func getCombinedWalletState(storage: WalletStorageInterface, subject: Com return storage.getWalletRecords() |> map { records -> CombinedWalletState? in for item in records { - if item.info.publicKey == walletInfo.publicKey { - return item.state + switch item.info { + case let .ready(itemInfo, _, state): + if itemInfo.publicKey == walletInfo.publicKey { + return state + } + case .imported: + break } } return nil @@ -904,7 +1013,7 @@ public func getCombinedWalletState(storage: WalletStorageInterface, subject: Com } return .single(.cached(cachedState)) |> then( - tonInstance.walletAddress(publicKey: walletInfo.publicKey) + tonInstance.walletAddress(publicKey: walletInfo.publicKey, rwalletInitialPublicKey: walletInfo.rWalletInitialPublicKey) |> castError(GetCombinedWalletStateError.self) |> mapToSignal { address -> Signal in @@ -981,8 +1090,13 @@ public func getCombinedWalletState(storage: WalletStorageInterface, subject: Com return storage.updateWalletRecords { records in var records = records for i in 0 ..< records.count { - if records[i].info.publicKey == walletInfo.publicKey { - records[i].state = combinedState + switch records[i].info { + case let .ready(itemInfo, exportCompleted, _): + if itemInfo.publicKey == walletInfo.publicKey { + records[i].info = .ready(info: itemInfo, exportCompleted: exportCompleted, state: combinedState) + } + case .imported: + break } } return records @@ -996,26 +1110,6 @@ public func getCombinedWalletState(storage: WalletStorageInterface, subject: Com } ) } - case let .address(address): - let updated = getWalletState(address: address, tonInstance: tonInstance) - |> mapError { _ -> GetCombinedWalletStateError in - return .generic - } - |> mapToSignal { walletState, syncUtime -> Signal in - let topTransactions: Signal<[WalletTransaction], GetCombinedWalletStateError> - - topTransactions = getWalletTransactions(address: address, previousId: nil, tonInstance: tonInstance) - |> mapError { _ -> GetCombinedWalletStateError in - return .generic - } - return topTransactions - |> mapToSignal { topTransactions -> Signal in - let combinedState = CombinedWalletState(walletState: walletState, timestamp: syncUtime, topTransactions: topTransactions, pendingTransactions: []) - return .single(.updated(combinedState)) - } - } - return .single(.cached(nil)) - |> then(updated) } } @@ -1042,7 +1136,7 @@ public struct SendGramsVerificationResult { } public func verifySendGramsRequestAndEstimateFees(tonInstance: TonInstance, walletInfo: WalletInfo, toAddress: String, amount: Int64, comment: Data, encryptComment: Bool, timeout: Int32) -> Signal { - return walletAddress(publicKey: walletInfo.publicKey, tonInstance: tonInstance) + return walletAddress(walletInfo: walletInfo, tonInstance: tonInstance) |> castError(SendGramsFromWalletError.self) |> mapToSignal { fromAddress -> Signal in struct QueryWithInfo { @@ -1074,7 +1168,7 @@ public func verifySendGramsRequestAndEstimateFees(tonInstance: TonInstance, wall } public func sendGramsFromWallet(storage: WalletStorageInterface, tonInstance: TonInstance, walletInfo: WalletInfo, decryptedSecret: Data, localPassword: Data, toAddress: String, amount: Int64, comment: Data, encryptComment: Bool, forceIfDestinationNotInitialized: Bool, timeout: Int32, randomId: Int64) -> Signal { - return walletAddress(publicKey: walletInfo.publicKey, tonInstance: tonInstance) + return walletAddress(walletInfo: walletInfo, tonInstance: tonInstance) |> castError(SendGramsFromWalletError.self) |> mapToSignal { fromAddress -> Signal in return tonInstance.prepareSendGramsFromWalletQuery(decryptedSecret: decryptedSecret, localPassword: localPassword, walletInfo: walletInfo, fromAddress: fromAddress, toAddress: toAddress, amount: amount, comment: comment, encryptComment: encryptComment, forceIfDestinationNotInitialized: forceIfDestinationNotInitialized, timeout: timeout, randomId: randomId) @@ -1094,11 +1188,14 @@ public func sendGramsFromWallet(storage: WalletStorageInterface, tonInstance: To return storage.updateWalletRecords { records in var records = records for i in 0 ..< records.count { - if records[i].info.publicKey == walletInfo.publicKey { - if var state = records[i].state { + switch records[i].info { + case let .ready(itemInfo, exportCompleted, itemState): + if itemInfo.publicKey == walletInfo.publicKey, var state = itemState { state.pendingTransactions.insert(result, at: 0) - records[i].state = state + records[i].info = .ready(info: itemInfo, exportCompleted: exportCompleted, state: state) } + case .imported: + break } } return records diff --git a/submodules/WalletUI/Sources/WalletInfoScreen.swift b/submodules/WalletUI/Sources/WalletInfoScreen.swift index 229939364c9..e198ab8fa67 100644 --- a/submodules/WalletUI/Sources/WalletInfoScreen.swift +++ b/submodules/WalletUI/Sources/WalletInfoScreen.swift @@ -44,7 +44,7 @@ private class WalletInfoTitleView: UIView, NavigationBarTitleView { public final class WalletInfoScreen: ViewController { private let context: WalletContext - private let walletInfo: WalletInfo? + private let walletInfo: WalletInfo private let address: String private let enableDebugActions: Bool @@ -55,7 +55,7 @@ public final class WalletInfoScreen: ViewController { return self._ready } - public init(context: WalletContext, walletInfo: WalletInfo?, address: String, enableDebugActions: Bool) { + public init(context: WalletContext, walletInfo: WalletInfo, address: String, enableDebugActions: Bool) { self.context = context self.walletInfo = walletInfo self.address = address @@ -73,9 +73,7 @@ public final class WalletInfoScreen: ViewController { self.navigationBar?.intrinsicCanTransitionInline = false self.navigationItem.backBarButtonItem = UIBarButtonItem(title: self.presentationData.strings.Wallet_Navigation_Back, style: .plain, target: nil, action: nil) - if let _ = walletInfo { - self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: generateTintedImage(image: UIImage(bundleImageName: "Wallet/NavigationSettingsIcon"), color: .white), style: .plain, target: self, action: #selector(self.settingsPressed)) - } + self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: generateTintedImage(image: UIImage(bundleImageName: "Wallet/NavigationSettingsIcon"), color: .white), style: .plain, target: self, action: #selector(self.settingsPressed)) self.navigationItem.titleView = WalletInfoTitleView(action: { [weak self] in self?.scrollToTop?() }) @@ -93,16 +91,15 @@ public final class WalletInfoScreen: ViewController { } @objc private func settingsPressed() { - if let walletInfo = self.walletInfo { - self.push(walletSettingsController(context: self.context, walletInfo: walletInfo)) - } + self.push(walletSettingsController(context: self.context, walletInfo: self.walletInfo)) } override public func loadDisplayNode() { self.displayNode = WalletInfoScreenNode(context: self.context, presentationData: self.presentationData, walletInfo: self.walletInfo, address: self.address, sendAction: { [weak self] in - guard let strongSelf = self, let walletInfo = strongSelf.walletInfo else { + guard let strongSelf = self else { return } + let walletInfo = strongSelf.walletInfo guard let combinedState = (strongSelf.displayNode as! WalletInfoScreenNode).combinedState else { return } @@ -122,10 +119,16 @@ public final class WalletInfoScreen: ViewController { strongSelf.push(walletSendScreen(context: strongSelf.context, randomId: randomId, walletInfo: walletInfo)) } }, receiveAction: { [weak self] in - guard let strongSelf = self, let _ = strongSelf.walletInfo else { + guard let strongSelf = self else { return } - strongSelf.push(WalletReceiveScreen(context: strongSelf.context, mode: .receive(address: strongSelf.address))) + let _ = (walletAddress(walletInfo: strongSelf.walletInfo, tonInstance: strongSelf.context.tonInstance) + |> deliverOnMainQueue).start(next: { address in + guard let strongSelf = self else { + return + } + strongSelf.push(WalletReceiveScreen(context: strongSelf.context, mode: .receive(address: address))) + }) }, openTransaction: { [weak self] transaction in guard let strongSelf = self else { return @@ -274,7 +277,8 @@ private final class WalletInfoHeaderNode: ASDisplayNode { let balanceNode: WalletInfoBalanceNode let refreshNode: WalletRefreshNode - private let balanceSubtitleNode: ImmediateTextNode + let balanceSubtitleNode: ImmediateTextNode + let balanceSubtitleIconNode: AnimatedStickerNode private let receiveButtonNode: SolidRoundedButtonNode private let receiveGramsButtonNode: SolidRoundedButtonNode private let sendButtonNode: SolidRoundedButtonNode @@ -288,7 +292,15 @@ private final class WalletInfoHeaderNode: ASDisplayNode { self.balanceSubtitleNode = ImmediateTextNode() self.balanceSubtitleNode.displaysAsynchronously = false - self.balanceSubtitleNode.attributedText = NSAttributedString(string: hasActions ? presentationData.strings.Wallet_Info_YourBalance : "balance", font: Font.regular(13), textColor: UIColor(white: 1.0, alpha: 0.6)) + self.balanceSubtitleNode.attributedText = NSAttributedString(string: presentationData.strings.Wallet_Info_YourBalance, font: Font.regular(13), textColor: UIColor(white: 1.0, alpha: 0.6)) + + self.balanceSubtitleIconNode = AnimatedStickerNode() + self.balanceSubtitleIconNode.isHidden = true + if let path = getAppBundle().path(forResource: "WalletIntroStatic", ofType: "tgs") { + self.balanceSubtitleIconNode.setup(source: AnimatedStickerNodeLocalFileSource(path: path), width: 36, height: 36, mode: .direct) + self.balanceSubtitleIconNode.visibility = true + } + self.balanceSubtitleNode.addSubnode(self.balanceSubtitleIconNode) self.headerBackgroundNode = ASDisplayNode() self.headerBackgroundNode.backgroundColor = .black @@ -353,6 +365,9 @@ private final class WalletInfoHeaderNode: ASDisplayNode { let buttonAlpha: CGFloat = buttonTransition let balanceSubtitleSize = self.balanceSubtitleNode.updateLayout(CGSize(width: size.width - sideInset * 2.0, height: 200.0)) + let balanceSubtitleIconSize = CGSize(width: 18.0, height: 18.0) + self.balanceSubtitleIconNode.frame = CGRect(origin: CGPoint(x: -balanceSubtitleIconSize.width - 2.0, y: -2.0), size: balanceSubtitleIconSize) + self.balanceSubtitleIconNode.updateLayout(size: balanceSubtitleIconSize) let headerScaleTransition: CGFloat = max(0.0, min(1.0, (effectiveOffset - minHeaderOffset) / (maxHeaderOffset - minHeaderOffset))) @@ -544,7 +559,7 @@ private func preparedTransition(from fromEntries: [WalletInfoListEntry], to toEn private final class WalletInfoScreenNode: ViewControllerTracingNode { private let context: WalletContext private var presentationData: WalletPresentationData - private let walletInfo: WalletInfo? + private let walletInfo: WalletInfo private let address: String private let openTransaction: (WalletInfoTransaction) -> Void @@ -585,7 +600,7 @@ private final class WalletInfoScreenNode: ViewControllerTracingNode { private var watchCombinedStateDisposable: Disposable? private var refreshProgressDisposable: Disposable? - init(context: WalletContext, presentationData: WalletPresentationData, walletInfo: WalletInfo?, address: String, sendAction: @escaping () -> Void, receiveAction: @escaping () -> Void, openTransaction: @escaping (WalletInfoTransaction) -> Void, present: @escaping (ViewController, Any?) -> Void) { + init(context: WalletContext, presentationData: WalletPresentationData, walletInfo: WalletInfo, address: String, sendAction: @escaping () -> Void, receiveAction: @escaping () -> Void, openTransaction: @escaping (WalletInfoTransaction) -> Void, present: @escaping (ViewController, Any?) -> Void) { self.context = context self.presentationData = presentationData self.walletInfo = walletInfo @@ -593,7 +608,7 @@ private final class WalletInfoScreenNode: ViewControllerTracingNode { self.openTransaction = openTransaction self.present = present - self.headerNode = WalletInfoHeaderNode(presentationData: presentationData, hasActions: walletInfo != nil, sendAction: sendAction, receiveAction: receiveAction) + self.headerNode = WalletInfoHeaderNode(presentationData: presentationData, hasActions: true, sendAction: sendAction, receiveAction: receiveAction) self.listNode = ListView() self.listNode.verticalScrollIndicatorColor = UIColor(white: 0.0, alpha: 0.3) @@ -681,60 +696,55 @@ private final class WalletInfoScreenNode: ViewControllerTracingNode { }, queue: .mainQueue()) self.updateTimestampTimer?.start() - let subject: CombinedWalletStateSubject - if let walletInfo = walletInfo { - subject = .wallet(walletInfo) + let subject: CombinedWalletStateSubject = .wallet(walletInfo) - let watchCombinedStateSignal = context.storage.watchWalletRecords() - |> map { records -> WalletStateRecord? in - for record in records { - if record.info.publicKey == walletInfo.publicKey { - return record + let watchCombinedStateSignal = context.storage.watchWalletRecords() + |> map { records -> CombinedWalletState? in + for record in records { + switch record.info { + case let .ready(itemInfo, _, state): + if itemInfo.publicKey == walletInfo.publicKey { + return state } + case .imported: + break } - return nil } - |> distinctUntilChanged - |> mapToSignal { wallet -> Signal in - guard let wallet = wallet, let state = wallet.state else { - return .single(nil) - } - return .single(state) + return nil + } + |> distinctUntilChanged + + let tonInstance = self.context.tonInstance + let decryptedWalletState = combineLatest(queue: .mainQueue(), + watchCombinedStateSignal, + self.transactionDecryptionKey.get() + ) + |> mapToSignal { maybeState, decryptionKey -> Signal in + guard let state = maybeState, let decryptionKey = decryptionKey else { + return .single(maybeState) } - - let tonInstance = self.context.tonInstance - let decryptedWalletState = combineLatest(queue: .mainQueue(), - watchCombinedStateSignal, - self.transactionDecryptionKey.get() - ) - |> mapToSignal { maybeState, decryptionKey -> Signal in - guard let state = maybeState, let decryptionKey = decryptionKey else { - return .single(maybeState) - } - return decryptWalletTransactions(decryptionKey: decryptionKey, transactions: state.topTransactions, tonInstance: tonInstance) - |> `catch` { _ -> Signal<[WalletTransaction], NoError> in - return .single(state.topTransactions) - } - |> map { transactions -> CombinedWalletState? in - return state.withTopTransactions(transactions) - } + return decryptWalletTransactions(decryptionKey: decryptionKey, transactions: state.topTransactions, tonInstance: tonInstance) + |> `catch` { _ -> Signal<[WalletTransaction], NoError> in + return .single(state.topTransactions) + } + |> map { transactions -> CombinedWalletState? in + return state.withTopTransactions(transactions) + } + } + + self.watchCombinedStateDisposable = (decryptedWalletState + |> deliverOnMainQueue).start(next: { [weak self] state in + guard let strongSelf = self, let state = state else { + return } - self.watchCombinedStateDisposable = (decryptedWalletState - |> deliverOnMainQueue).start(next: { [weak self] state in - guard let strongSelf = self, let state = state else { - return + if state.pendingTransactions != strongSelf.combinedState?.pendingTransactions || state.timestamp != strongSelf.combinedState?.timestamp { + if !strongSelf.reloadingState { + strongSelf.updateCombinedState(combinedState: state, isUpdated: true) } - - if state.pendingTransactions != strongSelf.combinedState?.pendingTransactions || state.timestamp != strongSelf.combinedState?.timestamp { - if !strongSelf.reloadingState { - strongSelf.updateCombinedState(combinedState: state, isUpdated: true) - } - } - }) - } else { - subject = .address(address) - } + } + }) + let pollCombinedState: Signal = ( getCombinedWalletState(storage: context.storage, subject: subject, tonInstance: context.tonInstance, onlyCached: false) |> ignoreValues @@ -908,12 +918,7 @@ private final class WalletInfoScreenNode: ViewControllerTracingNode { self.headerNode.isRefreshing = true self.headerNode.refreshNode.refreshProgress = 0.0 - let subject: CombinedWalletStateSubject - if let walletInfo = self.walletInfo { - subject = .wallet(walletInfo) - } else { - subject = .address(self.address) - } + let subject: CombinedWalletStateSubject = .wallet(self.walletInfo) let transactionDecryptionKey = self.transactionDecryptionKey let tonInstance = self.context.tonInstance @@ -1017,8 +1022,23 @@ private final class WalletInfoScreenNode: ViewControllerTracingNode { private func updateCombinedState(combinedState: CombinedWalletState?, isUpdated: Bool) { self.combinedState = combinedState if let combinedState = combinedState { - self.headerNode.balanceNode.balance = (formatBalanceText(max(0, combinedState.walletState.balance), decimalSeparator: self.presentationData.dateTimeFormat.decimalSeparator), .white) - self.headerNode.balance = max(0, combinedState.walletState.balance) + self.headerNode.balanceNode.balance = (formatBalanceText(max(0, combinedState.walletState.effectiveAvailableBalance), decimalSeparator: self.presentationData.dateTimeFormat.decimalSeparator), .white) + if let unlockedBalance = combinedState.walletState.unlockedBalance { + let lockedBalance = combinedState.walletState.totalBalance - unlockedBalance + + let balanceText = formatBalanceText(max(0, lockedBalance), decimalSeparator: self.presentationData.dateTimeFormat.decimalSeparator) + + let string = NSMutableAttributedString() + string.append(NSAttributedString(string: "\(balanceText)", font: Font.semibold(13), textColor: .white)) + string.append(NSAttributedString(string: " locked", font: Font.regular(13), textColor: .white)) + + self.headerNode.balanceSubtitleNode.attributedText = string + self.headerNode.balanceSubtitleIconNode.isHidden = false + } else { + self.headerNode.balanceSubtitleNode.attributedText = NSAttributedString(string: self.presentationData.strings.Wallet_Info_YourBalance, font: Font.regular(13), textColor: UIColor(white: 1.0, alpha: 0.6)) + self.headerNode.balanceSubtitleIconNode.isHidden = true + } + self.headerNode.balance = max(0, combinedState.walletState.effectiveAvailableBalance) if self.isReady, let (layout, navigationHeight) = self.validLayout { self.containerLayoutUpdated(layout: layout, navigationHeight: navigationHeight, transition: .immediate) @@ -1117,7 +1137,12 @@ private final class WalletInfoScreenNode: ViewControllerTracingNode { } let transactionDecryptionKey = self.transactionDecryptionKey let tonInstance = self.context.tonInstance - let processedTransactions = getWalletTransactions(address: self.address, previousId: lastTransactionId, tonInstance: self.context.tonInstance) + let requestTransactions = walletAddress(walletInfo: self.walletInfo, tonInstance: self.context.tonInstance) + |> castError(GetWalletTransactionsError.self) + |> mapToSignal { address -> Signal<[WalletTransaction], GetWalletTransactionsError> in + getWalletTransactions(address: address, previousId: lastTransactionId, tonInstance: tonInstance) + } + let processedTransactions = requestTransactions |> mapToSignal { transactions -> Signal<[WalletTransaction], GetWalletTransactionsError> in return transactionDecryptionKey.get() |> castError(GetWalletTransactionsError.self) diff --git a/submodules/WalletUI/Sources/WalletSendScreen.swift b/submodules/WalletUI/Sources/WalletSendScreen.swift index 45159e1196a..a3e6fef47b4 100644 --- a/submodules/WalletUI/Sources/WalletSendScreen.swift +++ b/submodules/WalletUI/Sources/WalletSendScreen.swift @@ -501,7 +501,7 @@ public func walletSendScreen(context: WalletContext, randomId: Int64, walletInfo }) } - let _ = (walletAddress(publicKey: walletInfo.publicKey, tonInstance: context.tonInstance) + let _ = (walletAddress(walletInfo: walletInfo, tonInstance: context.tonInstance) |> deliverOnMainQueue).start(next: { walletAddress in let presentationData = context.presentationData let state = stateValue.with { $0 } @@ -572,7 +572,7 @@ public func walletSendScreen(context: WalletContext, randomId: Int64, walletInfo var emptyItem: ItemListControllerEmptyStateItem? if let walletState = walletState { let textLength: Int = state.comment.data(using: .utf8, allowLossyConversion: true)?.count ?? 0 - sendEnabled = isValidAddress(state.address, exactLength: true) && amount > 0 && amount <= walletState.balance && textLength <= walletTextLimit + sendEnabled = isValidAddress(state.address, exactLength: true) && amount > 0 && amount <= walletState.effectiveAvailableBalance && textLength <= walletTextLimit rightNavigationButton = ItemListNavigationButton(content: .text(presentationData.strings.Wallet_Send_Send), style: .bold, enabled: sendEnabled, action: { arguments.proceed() @@ -583,7 +583,7 @@ public func walletSendScreen(context: WalletContext, randomId: Int64, walletInfo } let controllerState = ItemListControllerState(theme: presentationData.theme, title: .text(presentationData.strings.Wallet_Send_Title), leftNavigationButton: leftNavigationButton, rightNavigationButton: rightNavigationButton, backNavigationButton: ItemListBackButton(title: presentationData.strings.Wallet_Navigation_Back), animateChanges: false) - let listState = ItemListNodeState(entries: walletSendScreenEntries(presentationData: presentationData, balance: walletState?.balance, state: state, sendEnabled: sendEnabled), style: .blocks, focusItemTag: focusItemTag, emptyStateItem: emptyItem, animateChanges: false) + let listState = ItemListNodeState(entries: walletSendScreenEntries(presentationData: presentationData, balance: walletState?.effectiveAvailableBalance, state: state, sendEnabled: sendEnabled), style: .blocks, focusItemTag: focusItemTag, emptyStateItem: emptyItem, animateChanges: false) return (controllerState, (listState, arguments)) } diff --git a/submodules/WalletUI/Sources/WalletSplashScreen.swift b/submodules/WalletUI/Sources/WalletSplashScreen.swift index fba69552aa0..96ca943fcd0 100644 --- a/submodules/WalletUI/Sources/WalletSplashScreen.swift +++ b/submodules/WalletUI/Sources/WalletSplashScreen.swift @@ -48,7 +48,8 @@ public struct WalletSplashModeSending { public enum WalletSplashMode { case intro case created(walletInfo: WalletInfo, words: [String]?) - case success(walletInfo: WalletInfo) + case successfullyCreated(walletInfo: WalletInfo) + case successfullyImported(importedInfo: ImportedWalletInfo) case restoreFailed case sending(WalletSplashModeSending) case sent(walletInfo: WalletInfo, amount: Int64) @@ -56,16 +57,21 @@ public enum WalletSplashMode { case secureStorageReset(WalletSecureStorageResetReason) } +public struct WalletCreatedPreloadState { + let info: WalletInfo + let state: CombinedWalletStateResult +} + public final class WalletSplashScreen: ViewController { private let context: WalletContext private var presentationData: WalletPresentationData private var mode: WalletSplashMode - private let walletCreatedPreloadState: Promise? + private let walletCreatedPreloadState: Promise? private let actionDisposable = MetaDisposable() - public init(context: WalletContext, mode: WalletSplashMode, walletCreatedPreloadState: Promise?) { + public init(context: WalletContext, mode: WalletSplashMode, walletCreatedPreloadState: Promise?) { self.context = context self.mode = mode @@ -81,22 +87,70 @@ public final class WalletSplashScreen: ViewController { } else { self.walletCreatedPreloadState = Promise() self.walletCreatedPreloadState?.set(getCombinedWalletState(storage: context.storage, subject: .wallet(walletInfo), tonInstance: context.tonInstance, onlyCached: false) - |> map(Optional.init) - |> `catch` { _ -> Signal in + |> map { state -> WalletCreatedPreloadState? in + return WalletCreatedPreloadState(info: walletInfo, state: state) + } + |> `catch` { _ -> Signal in return .single(nil) }) } - case let .success(walletInfo): + case let .successfullyCreated(walletInfo): if let walletCreatedPreloadState = walletCreatedPreloadState { self.walletCreatedPreloadState = walletCreatedPreloadState } else { self.walletCreatedPreloadState = Promise() self.walletCreatedPreloadState?.set(getCombinedWalletState(storage: context.storage, subject: .wallet(walletInfo), tonInstance: context.tonInstance, onlyCached: false) - |> map(Optional.init) - |> `catch` { _ -> Signal in + |> map { state -> WalletCreatedPreloadState? in + return WalletCreatedPreloadState(info: walletInfo, state: state) + } + |> `catch` { _ -> Signal in return .single(nil) }) } + case let .successfullyImported(importedInfo): + if let walletCreatedPreloadState = walletCreatedPreloadState { + self.walletCreatedPreloadState = walletCreatedPreloadState + } else { + self.walletCreatedPreloadState = Promise() + + let signal = getWalletInfo(importedInfo: importedInfo, tonInstance: context.tonInstance) + |> mapError { error -> GetCombinedWalletStateError in + switch error { + case .generic: + return .generic + case .network: + return .network + } + } + |> mapToSignal { walletInfo -> Signal in + return context.storage.updateWalletRecords { records in + var records = records + for i in 0 ..< records.count { + switch records[i].info { + case .ready: + break + case let .imported(info): + if info.publicKey == importedInfo.publicKey { + records[i].info = .ready(info: walletInfo, exportCompleted: true, state: nil) + } + } + } + return records + } + |> castError(GetCombinedWalletStateError.self) + |> mapToSignal { _ -> Signal in + return getCombinedWalletState(storage: context.storage, subject: .wallet(walletInfo), tonInstance: context.tonInstance, onlyCached: false) + |> map { state -> WalletCreatedPreloadState? in + return WalletCreatedPreloadState(info: walletInfo, state: state) + } + } + } + |> `catch` { _ -> Signal in + return .single(nil) + } + + self.walletCreatedPreloadState?.set(signal) + } default: self.walletCreatedPreloadState = nil } @@ -139,7 +193,7 @@ public final class WalletSplashScreen: ViewController { self.navigationItem.setLeftBarButton(UIBarButtonItem(customDisplayNode: ASDisplayNode())!, animated: false) case .restoreFailed, .secureStorageNotAvailable, .secureStorageReset, .created: break - case .success: + case .successfullyCreated, .successfullyImported: break } @@ -197,7 +251,7 @@ public final class WalletSplashScreen: ViewController { return } if let navigationController = strongSelf.navigationController as? NavigationController { - let _ = (walletAddress(publicKey: walletInfo.publicKey, tonInstance: strongSelf.context.tonInstance) + let _ = (walletAddress(walletInfo: walletInfo, tonInstance: strongSelf.context.tonInstance) |> deliverOnMainQueue).start(next: { [weak self] address in guard let strongSelf = self else { return @@ -222,7 +276,7 @@ public final class WalletSplashScreen: ViewController { return } if let navigationController = strongSelf.navigationController as? NavigationController { - let _ = (walletAddress(publicKey: walletInfo.publicKey, tonInstance: strongSelf.context.tonInstance) + let _ = (walletAddress(walletInfo: walletInfo, tonInstance: strongSelf.context.tonInstance) |> deliverOnMainQueue).start(next: { [weak self] address in guard let strongSelf = self else { return @@ -315,7 +369,7 @@ public final class WalletSplashScreen: ViewController { return true } - let _ = (walletAddress(publicKey: sending.walletInfo.publicKey, tonInstance: self.context.tonInstance) + let _ = (walletAddress(walletInfo: sending.walletInfo, tonInstance: self.context.tonInstance) |> deliverOnMainQueue).start(next: { [weak self] address in guard let strongSelf = self else { return @@ -426,8 +480,8 @@ public final class WalletSplashScreen: ViewController { } }) } - case let .success(walletInfo): - let _ = (walletAddress(publicKey: walletInfo.publicKey, tonInstance: strongSelf.context.tonInstance) + case let .successfullyCreated(walletInfo): + let _ = (walletAddress(walletInfo: walletInfo, tonInstance: strongSelf.context.tonInstance) |> deliverOnMainQueue).start(next: { address in guard let strongSelf = self else { return @@ -452,6 +506,46 @@ public final class WalletSplashScreen: ViewController { navigationController.setViewControllers(controllers, animated: true) } }) + case .successfullyImported: + let controller = OverlayStatusController(theme: strongSelf.presentationData.theme, type: .loading(cancelled: nil)) + strongSelf.present(controller, in: .window(.root)) + + let _ = (strongSelf.walletCreatedPreloadState!.get() + |> filter { $0 != nil } + |> take(1) + |> deliverOnMainQueue).start(next: { state in + controller.dismiss() + + guard let state = state else { + return + } + let walletInfo = state.info + let _ = (walletAddress(walletInfo: walletInfo, tonInstance: strongSelf.context.tonInstance) + |> deliverOnMainQueue).start(next: { address in + guard let strongSelf = self else { + return + } + + if let navigationController = strongSelf.navigationController as? NavigationController { + var controllers = navigationController.viewControllers + controllers = controllers.filter { controller in + if controller is WalletSplashScreen { + return false + } + if controller is WalletWordDisplayScreen { + return false + } + if controller is WalletWordCheckScreen { + return false + } + return true + } + controllers.append(WalletInfoScreen(context: strongSelf.context, walletInfo: walletInfo, address: address, enableDebugActions: false)) + strongSelf.view.endEditing(true) + navigationController.setViewControllers(controllers, animated: true) + } + }) + }) case let .sent(walletInfo, _): if let navigationController = strongSelf.navigationController as? NavigationController { var controllers = navigationController.viewControllers @@ -474,7 +568,7 @@ public final class WalletSplashScreen: ViewController { return true } - let _ = (walletAddress(publicKey: walletInfo.publicKey, tonInstance: strongSelf.context.tonInstance) + let _ = (walletAddress(walletInfo: walletInfo, tonInstance: strongSelf.context.tonInstance) |> deliverOnMainQueue).start(next: { [weak self] address in guard let strongSelf = self else { return @@ -527,7 +621,7 @@ public final class WalletSplashScreen: ViewController { return true } - let _ = (walletAddress(publicKey: sending.walletInfo.publicKey, tonInstance: strongSelf.context.tonInstance) + let _ = (walletAddress(walletInfo: sending.walletInfo, tonInstance: strongSelf.context.tonInstance) |> deliverOnMainQueue).start(next: { [weak self] address in guard let strongSelf = self else { return @@ -627,7 +721,7 @@ private final class WalletSplashScreenNode: ViewControllerTracingNode { } } - init(context: WalletContext, walletCreatedPreloadState: Promise?, presentationData: WalletPresentationData, mode: WalletSplashMode, action: @escaping () -> Void, secondaryAction: @escaping () -> Void, openTerms: @escaping () -> Void) { + init(context: WalletContext, walletCreatedPreloadState: Promise?, presentationData: WalletPresentationData, mode: WalletSplashMode, action: @escaping () -> Void, secondaryAction: @escaping () -> Void, openTerms: @escaping () -> Void) { self.presentationData = presentationData self.mode = mode self.secondaryAction = secondaryAction @@ -680,7 +774,7 @@ private final class WalletSplashScreenNode: ViewControllerTracingNode { self.animationNode.visibility = true } secondaryActionText = "" - case .success: + case .successfullyCreated, .successfullyImported: title = self.presentationData.strings.Wallet_Completed_Title text = NSAttributedString(string: self.presentationData.strings.Wallet_Completed_Text, font: textFont, textColor: textColor) buttonText = self.presentationData.strings.Wallet_Completed_ViewWallet @@ -899,7 +993,7 @@ private final class WalletSplashScreenNode: ViewControllerTracingNode { let iconSize: CGSize = self.animationSize var iconOffset = CGPoint() switch self.mode { - case .success: + case .successfullyCreated, .successfullyImported: iconOffset.x = 10.0 default: break diff --git a/submodules/WalletUI/Sources/WalletWordCheckScreen.swift b/submodules/WalletUI/Sources/WalletWordCheckScreen.swift index 076dcd7f462..1e268ed5ae8 100644 --- a/submodules/WalletUI/Sources/WalletWordCheckScreen.swift +++ b/submodules/WalletUI/Sources/WalletWordCheckScreen.swift @@ -2073,9 +2073,9 @@ public final class WalletWordCheckScreen: ViewController { private let startTime: Double - private let walletCreatedPreloadState: Promise? + private let walletCreatedPreloadState: Promise? - public init(context: WalletContext, mode: WalletWordCheckMode, walletCreatedPreloadState: Promise?) { + public init(context: WalletContext, mode: WalletWordCheckMode, walletCreatedPreloadState: Promise?) { self.context = context self.mode = mode self.walletCreatedPreloadState = walletCreatedPreloadState @@ -2137,7 +2137,7 @@ public final class WalletWordCheckScreen: ViewController { return true } let _ = confirmWalletExported(storage: strongSelf.context.storage, publicKey: walletInfo.publicKey).start() - controllers.append(WalletSplashScreen(context: strongSelf.context, mode: .success(walletInfo: walletInfo), walletCreatedPreloadState: strongSelf.walletCreatedPreloadState)) + controllers.append(WalletSplashScreen(context: strongSelf.context, mode: .successfullyCreated(walletInfo: walletInfo), walletCreatedPreloadState: strongSelf.walletCreatedPreloadState)) strongSelf.view.endEditing(true) navigationController.setViewControllers(controllers, animated: true) } @@ -2205,7 +2205,7 @@ public final class WalletWordCheckScreen: ViewController { } return true } - controllers.append(WalletSplashScreen(context: strongSelf.context, mode: .success(walletInfo: walletInfo), walletCreatedPreloadState: strongSelf.walletCreatedPreloadState)) + controllers.append(WalletSplashScreen(context: strongSelf.context, mode: .successfullyImported(importedInfo: walletInfo), walletCreatedPreloadState: strongSelf.walletCreatedPreloadState)) strongSelf.view.endEditing(true) navigationController.setViewControllers(controllers, animated: true) } diff --git a/submodules/WalletUI/Sources/WalletWordDisplayScreen.swift b/submodules/WalletUI/Sources/WalletWordDisplayScreen.swift index 34cb938aa6d..953f764e408 100644 --- a/submodules/WalletUI/Sources/WalletWordDisplayScreen.swift +++ b/submodules/WalletUI/Sources/WalletWordDisplayScreen.swift @@ -24,9 +24,9 @@ public final class WalletWordDisplayScreen: ViewController { private let startTime: Double private let idleTimerExtensionDisposable: Disposable - private let walletCreatedPreloadState: Promise? + private let walletCreatedPreloadState: Promise? - public init(context: WalletContext, walletInfo: WalletInfo, wordList: [String], mode: WalletWordDisplayScreenMode, walletCreatedPreloadState: Promise?) { + public init(context: WalletContext, walletInfo: WalletInfo, wordList: [String], mode: WalletWordDisplayScreenMode, walletCreatedPreloadState: Promise?) { self.context = context self.walletInfo = walletInfo self.wordList = wordList diff --git a/submodules/ton/tonlib-src/CMakeLists.txt b/submodules/ton/tonlib-src/CMakeLists.txt index 605410236e7..c98edaa5864 100644 --- a/submodules/ton/tonlib-src/CMakeLists.txt +++ b/submodules/ton/tonlib-src/CMakeLists.txt @@ -104,6 +104,7 @@ if (TON_USE_ROCKSDB) if (ANDROID) set(PORTABLE ON CACHE BOOL "portable") endif() + set(WITH_GFLAGS OFF CACHE BOOL "build with GFlags") set(WITH_TESTS OFF CACHE BOOL "build with tests") set(WITH_TOOLS OFF CACHE BOOL "build with tools") set(FAIL_ON_WARNINGS OFF CACHE BOOL "fail on warnings") @@ -220,7 +221,7 @@ elseif (CLANG OR GCC) if (APPLE) #use "-Wl,-exported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/export_list" for exported symbols set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fvisibility=hidden -Wl,-dead_strip,-x,-S") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fvisibility=hidden -Wl,-dead_strip,-x,-S") + #set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fvisibility=hidden -Wl,-dead_strip,-x,-S") else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffunction-sections -fdata-sections") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--gc-sections -Wl,--exclude-libs,ALL") diff --git a/submodules/ton/tonlib-src/crypto/CMakeLists.txt b/submodules/ton/tonlib-src/crypto/CMakeLists.txt index f2865f5530b..d8efc5862df 100644 --- a/submodules/ton/tonlib-src/crypto/CMakeLists.txt +++ b/submodules/ton/tonlib-src/crypto/CMakeLists.txt @@ -49,6 +49,7 @@ set(TON_CRYPTO_SOURCE common/bigexp.h common/util.h common/linalloc.hpp + common/promiseop.hpp ellcurve/Ed25519.h ellcurve/Fp25519.h @@ -212,6 +213,7 @@ set(SMC_ENVELOPE_SOURCE smc-envelope/HighloadWalletV2.cpp smc-envelope/ManualDns.cpp smc-envelope/MultisigWallet.cpp + smc-envelope/PaymentChannel.cpp smc-envelope/SmartContract.cpp smc-envelope/SmartContractCode.cpp smc-envelope/TestGiver.cpp @@ -341,7 +343,7 @@ if (NOT CMAKE_CROSSCOMPILING) set(multiValueArgs SOURCE) set(FUNC_LIB_SOURCE smartcont/stdlib.fc) cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) - string(REGEX REPLACE "[^a-zA-Z_]" "_" ID ${ARG_DEST}) + string(REGEX REPLACE "[^0-9a-zA-Z_]" "_" ID ${ARG_DEST}) set(ARG_DEST_FIF "${ARG_DEST}.fif") add_custom_command( COMMENT "Generate ${ARG_DEST_FIF}" @@ -374,10 +376,13 @@ if (NOT CMAKE_CROSSCOMPILING) GenFif(DEST smartcont/auto/multisig-code SOURCE smartcont/multisig-code.fc NAME multisig) GenFif(DEST smartcont/auto/restricted-wallet-code SOURCE smartcont/restricted-wallet-code.fc NAME restricted-wallet) GenFif(DEST smartcont/auto/restricted-wallet2-code SOURCE smartcont/restricted-wallet2-code.fc NAME restricted-wallet2) + GenFif(DEST smartcont/auto/restricted-wallet3-code SOURCE smartcont/restricted-wallet3-code.fc NAME restricted-wallet3) GenFif(DEST smartcont/auto/dns-manual-code SOURCE smartcont/dns-manual-code.fc NAME dns-manual) GenFif(DEST smartcont/auto/dns-auto-code SOURCE smartcont/dns-auto-code.fc NAME dns-auto) + GenFif(DEST smartcont/auto/payment-channel-code SOURCE smartcont/payment-channel-code.fc NAME payment-channel) + GenFif(DEST smartcont/auto/simple-wallet-ext-code SOURCE smartcont/simple-wallet-ext-code.fc NAME simple-wallet-ext) endif() @@ -420,5 +425,13 @@ if (WINGETOPT_FOUND) target_link_libraries_system(dump-block wingetopt) endif() +add_executable(test-weight-distr block/test-weight-distr.cpp) +target_include_directories(test-weight-distr PUBLIC $ + $) +target_link_libraries(test-weight-distr PUBLIC ton_crypto fift-lib ton_block) +if (WINGETOPT_FOUND) + target_link_libraries_system(test-weight-distr wingetopt) +endif() + install(TARGETS fift func RUNTIME DESTINATION bin) install(DIRECTORY fift/lib/ DESTINATION lib/fift) diff --git a/submodules/ton/tonlib-src/crypto/block/block-auto.cpp b/submodules/ton/tonlib-src/crypto/block/block-auto.cpp index 74778d6e6f2..1963f1619bc 100644 --- a/submodules/ton/tonlib-src/crypto/block/block-auto.cpp +++ b/submodules/ton/tonlib-src/crypto/block/block-auto.cpp @@ -27,6 +27,7 @@ // uses built-in type `uint256` // uses built-in type `int257` // uses built-in type `bits256` +// uses built-in type `bits512` namespace block { @@ -7724,6 +7725,82 @@ bool HASH_UPDATE::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { } +// +// code for type `MERKLE_PROOF` +// +constexpr unsigned char MERKLE_PROOF::cons_tag[1]; + +int MERKLE_PROOF::check_tag(const vm::CellSlice& cs) const { + return cs.prefetch_ulong(8) == 3 ? _merkle_proof : -1; +} + +bool MERKLE_PROOF::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + return cs.fetch_ulong(8) == 3 + && cs.advance(272) + && X_.validate_skip_ref(ops, cs, weak); +} + +bool MERKLE_PROOF::unpack(vm::CellSlice& cs, MERKLE_PROOF::Record& data) const { + return cs.fetch_ulong(8) == 3 + && cs.fetch_bits_to(data.virtual_hash.bits(), 256) + && cs.fetch_uint_to(16, data.depth) + && cs.fetch_ref_to(data.virtual_root); +} + +bool MERKLE_PROOF::unpack__merkle_proof(vm::CellSlice& cs, td::BitArray<256>& virtual_hash, int& depth, Ref& virtual_root) const { + return cs.fetch_ulong(8) == 3 + && cs.fetch_bits_to(virtual_hash.bits(), 256) + && cs.fetch_uint_to(16, depth) + && cs.fetch_ref_to(virtual_root); +} + +bool MERKLE_PROOF::cell_unpack(Ref cell_ref, MERKLE_PROOF::Record& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool MERKLE_PROOF::cell_unpack__merkle_proof(Ref cell_ref, td::BitArray<256>& virtual_hash, int& depth, Ref& virtual_root) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack__merkle_proof(cs, virtual_hash, depth, virtual_root) && cs.empty_ext(); +} + +bool MERKLE_PROOF::pack(vm::CellBuilder& cb, const MERKLE_PROOF::Record& data) const { + return cb.store_long_bool(3, 8) + && cb.store_bits_bool(data.virtual_hash.cbits(), 256) + && cb.store_ulong_rchk_bool(data.depth, 16) + && cb.store_ref_bool(data.virtual_root); +} + +bool MERKLE_PROOF::pack__merkle_proof(vm::CellBuilder& cb, td::BitArray<256> virtual_hash, int depth, Ref virtual_root) const { + return cb.store_long_bool(3, 8) + && cb.store_bits_bool(virtual_hash.cbits(), 256) + && cb.store_ulong_rchk_bool(depth, 16) + && cb.store_ref_bool(virtual_root); +} + +bool MERKLE_PROOF::cell_pack(Ref& cell_ref, const MERKLE_PROOF::Record& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool MERKLE_PROOF::cell_pack__merkle_proof(Ref& cell_ref, td::BitArray<256> virtual_hash, int depth, Ref virtual_root) const { + vm::CellBuilder cb; + return pack__merkle_proof(cb, virtual_hash, depth, std::move(virtual_root)) && std::move(cb).finalize_to(cell_ref); +} + +bool MERKLE_PROOF::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + return cs.fetch_ulong(8) == 3 + && pp.open("!merkle_proof") + && pp.fetch_bits_field(cs, 256, "virtual_hash") + && pp.fetch_uint_field(cs, 16, "depth") + && pp.field("virtual_root") + && X_.print_ref(pp, cs.fetch_ref()) + && pp.close(); +} + + // // code for type `AccountBlock` // @@ -18691,62 +18768,215 @@ bool TopBlockDescrSet::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { const TopBlockDescrSet t_TopBlockDescrSet; // -// code for type `ComplaintDescr` +// code for type `ProducerInfo` // -constexpr unsigned ComplaintDescr::cons_tag[1]; +constexpr unsigned char ProducerInfo::cons_tag[1]; -int ComplaintDescr::check_tag(const vm::CellSlice& cs) const { - return cs.prefetch_ulong(32) == 0x7e545dda ? no_blk_gen : -1; +int ProducerInfo::check_tag(const vm::CellSlice& cs) const { + return cs.prefetch_ulong(8) == 0x34 ? prod_info : -1; } -bool ComplaintDescr::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { - return cs.fetch_ulong(32) == 0x7e545dda - && cs.advance_ext(0x202a0); +bool ProducerInfo::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + return cs.fetch_ulong(8) == 0x34 + && cs.advance(640) + && t_MERKLE_PROOF_Block.validate_skip_ref(ops, cs, weak) + && t_MERKLE_PROOF_ShardState.validate_skip_ref(ops, cs, weak); } -bool ComplaintDescr::unpack(vm::CellSlice& cs, ComplaintDescr::Record& data) const { - return cs.fetch_ulong(32) == 0x7e545dda +bool ProducerInfo::unpack(vm::CellSlice& cs, ProducerInfo::Record& data) const { + return cs.fetch_ulong(8) == 0x34 + && cs.fetch_uint_to(32, data.utime) && cs.fetch_subslice_to(608, data.mc_blk_ref) - && cs.fetch_uint_to(32, data.from_utime) - && cs.fetch_uint_to(32, data.to_utime) && cs.fetch_ref_to(data.state_proof) && cs.fetch_ref_to(data.prod_proof); } -bool ComplaintDescr::cell_unpack(Ref cell_ref, ComplaintDescr::Record& data) const { +bool ProducerInfo::cell_unpack(Ref cell_ref, ProducerInfo::Record& data) const { if (cell_ref.is_null()) { return false; } auto cs = load_cell_slice(std::move(cell_ref)); return unpack(cs, data) && cs.empty_ext(); } -bool ComplaintDescr::pack(vm::CellBuilder& cb, const ComplaintDescr::Record& data) const { - return cb.store_long_bool(0x7e545dda, 32) +bool ProducerInfo::pack(vm::CellBuilder& cb, const ProducerInfo::Record& data) const { + return cb.store_long_bool(0x34, 8) + && cb.store_ulong_rchk_bool(data.utime, 32) && cb.append_cellslice_chk(data.mc_blk_ref, 608) - && cb.store_ulong_rchk_bool(data.from_utime, 32) - && cb.store_ulong_rchk_bool(data.to_utime, 32) && cb.store_ref_bool(data.state_proof) && cb.store_ref_bool(data.prod_proof); } -bool ComplaintDescr::cell_pack(Ref& cell_ref, const ComplaintDescr::Record& data) const { +bool ProducerInfo::cell_pack(Ref& cell_ref, const ProducerInfo::Record& data) const { vm::CellBuilder cb; return pack(cb, data) && std::move(cb).finalize_to(cell_ref); } -bool ComplaintDescr::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { - return cs.fetch_ulong(32) == 0x7e545dda - && pp.open("no_blk_gen") +bool ProducerInfo::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + return cs.fetch_ulong(8) == 0x34 + && pp.open("prod_info") + && pp.fetch_uint_field(cs, 32, "utime") && pp.field("mc_blk_ref") && t_ExtBlkRef.print_skip(pp, cs) - && pp.fetch_uint_field(cs, 32, "from_utime") - && pp.fetch_uint_field(cs, 32, "to_utime") && pp.field("state_proof") - && t_Anything.print_ref(pp, cs.fetch_ref()) + && t_MERKLE_PROOF_Block.print_ref(pp, cs.fetch_ref()) && pp.field("prod_proof") - && t_Anything.print_ref(pp, cs.fetch_ref()) + && t_MERKLE_PROOF_ShardState.print_ref(pp, cs.fetch_ref()) && pp.close(); } +const ProducerInfo t_ProducerInfo; + +// +// code for type `ComplaintDescr` +// +constexpr unsigned ComplaintDescr::cons_tag[2]; + +int ComplaintDescr::check_tag(const vm::CellSlice& cs) const { + switch (get_tag(cs)) { + case no_blk_gen: + return cs.prefetch_ulong(32) == 0x450e8bd9 ? no_blk_gen : -1; + case no_blk_gen_diff: + return cs.prefetch_ulong(32) == 0xc737b0caU ? no_blk_gen_diff : -1; + } + return -1; +} + +bool ComplaintDescr::skip(vm::CellSlice& cs) const { + switch (get_tag(cs)) { + case no_blk_gen: + return cs.advance_ext(0x10040); + case no_blk_gen_diff: + return cs.advance_ext(0x20020); + } + return false; +} + +bool ComplaintDescr::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + switch (get_tag(cs)) { + case no_blk_gen: + return cs.fetch_ulong(32) == 0x450e8bd9 + && cs.advance(32) + && t_ProducerInfo.validate_skip_ref(ops, cs, weak); + case no_blk_gen_diff: + return cs.fetch_ulong(32) == 0xc737b0caU + && t_ProducerInfo.validate_skip_ref(ops, cs, weak) + && t_ProducerInfo.validate_skip_ref(ops, cs, weak); + } + return false; +} + +bool ComplaintDescr::unpack(vm::CellSlice& cs, ComplaintDescr::Record_no_blk_gen& data) const { + return cs.fetch_ulong(32) == 0x450e8bd9 + && cs.fetch_uint_to(32, data.from_utime) + && cs.fetch_ref_to(data.prod_info); +} + +bool ComplaintDescr::unpack_no_blk_gen(vm::CellSlice& cs, unsigned& from_utime, Ref& prod_info) const { + return cs.fetch_ulong(32) == 0x450e8bd9 + && cs.fetch_uint_to(32, from_utime) + && cs.fetch_ref_to(prod_info); +} + +bool ComplaintDescr::cell_unpack(Ref cell_ref, ComplaintDescr::Record_no_blk_gen& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ComplaintDescr::cell_unpack_no_blk_gen(Ref cell_ref, unsigned& from_utime, Ref& prod_info) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack_no_blk_gen(cs, from_utime, prod_info) && cs.empty_ext(); +} + +bool ComplaintDescr::unpack(vm::CellSlice& cs, ComplaintDescr::Record_no_blk_gen_diff& data) const { + return cs.fetch_ulong(32) == 0xc737b0caU + && cs.fetch_ref_to(data.prod_info_old) + && cs.fetch_ref_to(data.prod_info_new); +} + +bool ComplaintDescr::unpack_no_blk_gen_diff(vm::CellSlice& cs, Ref& prod_info_old, Ref& prod_info_new) const { + return cs.fetch_ulong(32) == 0xc737b0caU + && cs.fetch_ref_to(prod_info_old) + && cs.fetch_ref_to(prod_info_new); +} + +bool ComplaintDescr::cell_unpack(Ref cell_ref, ComplaintDescr::Record_no_blk_gen_diff& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ComplaintDescr::cell_unpack_no_blk_gen_diff(Ref cell_ref, Ref& prod_info_old, Ref& prod_info_new) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack_no_blk_gen_diff(cs, prod_info_old, prod_info_new) && cs.empty_ext(); +} + +bool ComplaintDescr::pack(vm::CellBuilder& cb, const ComplaintDescr::Record_no_blk_gen& data) const { + return cb.store_long_bool(0x450e8bd9, 32) + && cb.store_ulong_rchk_bool(data.from_utime, 32) + && cb.store_ref_bool(data.prod_info); +} + +bool ComplaintDescr::pack_no_blk_gen(vm::CellBuilder& cb, unsigned from_utime, Ref prod_info) const { + return cb.store_long_bool(0x450e8bd9, 32) + && cb.store_ulong_rchk_bool(from_utime, 32) + && cb.store_ref_bool(prod_info); +} + +bool ComplaintDescr::cell_pack(Ref& cell_ref, const ComplaintDescr::Record_no_blk_gen& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ComplaintDescr::cell_pack_no_blk_gen(Ref& cell_ref, unsigned from_utime, Ref prod_info) const { + vm::CellBuilder cb; + return pack_no_blk_gen(cb, from_utime, std::move(prod_info)) && std::move(cb).finalize_to(cell_ref); +} + +bool ComplaintDescr::pack(vm::CellBuilder& cb, const ComplaintDescr::Record_no_blk_gen_diff& data) const { + return cb.store_long_bool(0xc737b0caU, 32) + && cb.store_ref_bool(data.prod_info_old) + && cb.store_ref_bool(data.prod_info_new); +} + +bool ComplaintDescr::pack_no_blk_gen_diff(vm::CellBuilder& cb, Ref prod_info_old, Ref prod_info_new) const { + return cb.store_long_bool(0xc737b0caU, 32) + && cb.store_ref_bool(prod_info_old) + && cb.store_ref_bool(prod_info_new); +} + +bool ComplaintDescr::cell_pack(Ref& cell_ref, const ComplaintDescr::Record_no_blk_gen_diff& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ComplaintDescr::cell_pack_no_blk_gen_diff(Ref& cell_ref, Ref prod_info_old, Ref prod_info_new) const { + vm::CellBuilder cb; + return pack_no_blk_gen_diff(cb, std::move(prod_info_old), std::move(prod_info_new)) && std::move(cb).finalize_to(cell_ref); +} + +bool ComplaintDescr::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + switch (get_tag(cs)) { + case no_blk_gen: + return cs.fetch_ulong(32) == 0x450e8bd9 + && pp.open("no_blk_gen") + && pp.fetch_uint_field(cs, 32, "from_utime") + && pp.field("prod_info") + && t_ProducerInfo.print_ref(pp, cs.fetch_ref()) + && pp.close(); + case no_blk_gen_diff: + return cs.fetch_ulong(32) == 0xc737b0caU + && pp.open("no_blk_gen_diff") + && pp.field("prod_info_old") + && t_ProducerInfo.print_ref(pp, cs.fetch_ref()) + && pp.field("prod_info_new") + && t_ProducerInfo.print_ref(pp, cs.fetch_ref()) + && pp.close(); + } + return pp.fail("unknown constructor for ComplaintDescr"); +} + const ComplaintDescr t_ComplaintDescr; // @@ -22336,58 +22566,844 @@ bool SmcCapability::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { const SmcCapability t_SmcCapability; -// definitions of constant types used +// +// code for type `ChanConfig` +// -const NatWidth t_natwidth_1{1}; -const NatWidth t_natwidth_9{9}; -const NatLeq t_natleq_30{30}; -const Maybe t_Maybe_Anycast{t_Anycast}; -const Int t_int8{8}; -const Bits t_bits256{256}; -const Int t_int32{32}; -const VarUInteger t_VarUInteger_16{16}; -const VarUInteger t_VarUInteger_32{32}; -const HashmapE t_HashmapE_32_VarUInteger_32{32, t_VarUInteger_32}; -const UInt t_uint64{64}; -const UInt t_uint32{32}; -const NatWidth t_natwidth_5{5}; -const Maybe t_Maybe_natwidth_5{t_natwidth_5}; -const Maybe t_Maybe_TickTock{t_TickTock}; -const Maybe t_Maybe_Ref_Cell{t_RefCell}; -const HashmapE t_HashmapE_256_SimpleLib{256, t_SimpleLib}; -const RefT t_Ref_StateInit{t_StateInit}; -const Either t_Either_StateInit_Ref_StateInit{t_StateInit, t_Ref_StateInit}; -const Maybe t_Maybe_Either_StateInit_Ref_StateInit{t_Either_StateInit_Ref_StateInit}; -const Message t_Message_Any{t_Anything}; -const NatLeq t_natleq_96{96}; -const RefT t_Ref_Message_Any{t_Message_Any}; -const RefT t_Ref_Transaction{t_Transaction}; -const RefT t_Ref_MsgEnvelope{t_MsgEnvelope}; -const HashmapAugE t_HashmapAugE_256_InMsg_ImportFees{256, t_InMsg, t_ImportFees}; -const RefT t_Ref_InMsg{t_InMsg}; -const UInt t_uint63{63}; -const HashmapAugE t_HashmapAugE_256_OutMsg_CurrencyCollection{256, t_OutMsg, t_CurrencyCollection}; -const HashmapAugE t_HashmapAugE_352_EnqueuedMsg_uint64{352, t_EnqueuedMsg, t_uint64}; -const HashmapE t_HashmapE_96_ProcessedUpto{96, t_ProcessedUpto}; -const HashmapE t_HashmapE_320_IhrPendingSince{320, t_IhrPendingSince}; -const VarUInteger t_VarUInteger_7{7}; -const Maybe t_Maybe_Grams{t_Grams}; -const RefT t_Ref_Account{t_Account}; -const HashmapAugE t_HashmapAugE_256_ShardAccount_DepthBalanceInfo{256, t_ShardAccount, t_DepthBalanceInfo}; -const UInt t_uint15{15}; -const Maybe t_Maybe_Ref_Message_Any{t_Ref_Message_Any}; -const HashmapE t_HashmapE_15_Ref_Message_Any{15, t_Ref_Message_Any}; -const RefT t_Ref_TYPE_1614{t_Transaction_aux}; -const HASH_UPDATE t_HASH_UPDATE_Account{t_Account}; -const RefT t_Ref_HASH_UPDATE_Account{t_HASH_UPDATE_Account}; -const RefT t_Ref_TransactionDescr{t_TransactionDescr}; -const HashmapAug t_HashmapAug_64_Ref_Transaction_CurrencyCollection{64, t_Ref_Transaction, t_CurrencyCollection}; -const HashmapAugE t_HashmapAugE_256_AccountBlock_CurrencyCollection{256, t_AccountBlock, t_CurrencyCollection}; -const VarUInteger t_VarUInteger_3{3}; -const Maybe t_Maybe_VarUInteger_3{t_VarUInteger_3}; -const Maybe t_Maybe_int32{t_int32}; -const RefT t_Ref_TYPE_1625{t_TrComputePhase_aux}; -const UInt t_uint16{16}; +int ChanConfig::check_tag(const vm::CellSlice& cs) const { + return chan_config; +} + +bool ChanConfig::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + return cs.advance(576) + && t_MsgAddressInt.validate_skip_ref(ops, cs, weak) + && t_MsgAddressInt.validate_skip_ref(ops, cs, weak) + && cs.advance(64); +} + +bool ChanConfig::unpack(vm::CellSlice& cs, ChanConfig::Record& data) const { + return cs.fetch_uint_to(32, data.init_timeout) + && cs.fetch_uint_to(32, data.close_timeout) + && cs.fetch_bits_to(data.a_key.bits(), 256) + && cs.fetch_bits_to(data.b_key.bits(), 256) + && cs.fetch_ref_to(data.a_addr) + && cs.fetch_ref_to(data.b_addr) + && cs.fetch_uint_to(64, data.channel_id); +} + +bool ChanConfig::cell_unpack(Ref cell_ref, ChanConfig::Record& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanConfig::pack(vm::CellBuilder& cb, const ChanConfig::Record& data) const { + return cb.store_ulong_rchk_bool(data.init_timeout, 32) + && cb.store_ulong_rchk_bool(data.close_timeout, 32) + && cb.store_bits_bool(data.a_key.cbits(), 256) + && cb.store_bits_bool(data.b_key.cbits(), 256) + && cb.store_ref_bool(data.a_addr) + && cb.store_ref_bool(data.b_addr) + && cb.store_ulong_rchk_bool(data.channel_id, 64); +} + +bool ChanConfig::cell_pack(Ref& cell_ref, const ChanConfig::Record& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanConfig::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + return pp.open("chan_config") + && pp.fetch_uint_field(cs, 32, "init_timeout") + && pp.fetch_uint_field(cs, 32, "close_timeout") + && pp.fetch_bits_field(cs, 256, "a_key") + && pp.fetch_bits_field(cs, 256, "b_key") + && pp.field("a_addr") + && t_MsgAddressInt.print_ref(pp, cs.fetch_ref()) + && pp.field("b_addr") + && t_MsgAddressInt.print_ref(pp, cs.fetch_ref()) + && pp.fetch_uint_field(cs, 64, "channel_id") + && pp.close(); +} + +const ChanConfig t_ChanConfig; + +// +// code for type `ChanState` +// + +int ChanState::check_tag(const vm::CellSlice& cs) const { + switch (get_tag(cs)) { + case chan_state_init: + return cs.have(3) ? chan_state_init : -1; + case chan_state_close: + return cs.have(3) ? chan_state_close : -1; + case chan_state_payout: + return cs.prefetch_ulong(3) == 2 ? chan_state_payout : -1; + } + return -1; +} + +bool ChanState::skip(vm::CellSlice& cs) const { + switch (get_tag(cs)) { + case chan_state_init: + return cs.advance(5) + && t_Grams.skip(cs) + && t_Grams.skip(cs) + && cs.advance(32) + && t_Grams.skip(cs) + && t_Grams.skip(cs); + case chan_state_close: + return cs.advance(5) + && t_Grams.skip(cs) + && t_Grams.skip(cs) + && cs.advance(32) + && t_Grams.skip(cs) + && t_Grams.skip(cs); + case chan_state_payout: + return cs.advance(3) + && t_Grams.skip(cs) + && t_Grams.skip(cs); + } + return false; +} + +bool ChanState::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + switch (get_tag(cs)) { + case chan_state_init: + return cs.advance(5) + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak) + && cs.advance(32) + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak); + case chan_state_close: + return cs.advance(5) + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak) + && cs.advance(32) + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak); + case chan_state_payout: + return cs.fetch_ulong(3) == 2 + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak); + } + return false; +} + +bool ChanState::unpack(vm::CellSlice& cs, ChanState::Record_chan_state_init& data) const { + return cs.fetch_ulong(3) == 0 + && cs.fetch_bool_to(data.signed_A) + && cs.fetch_bool_to(data.signed_B) + && t_Grams.fetch_to(cs, data.min_A) + && t_Grams.fetch_to(cs, data.min_B) + && cs.fetch_uint_to(32, data.expire_at) + && t_Grams.fetch_to(cs, data.A) + && t_Grams.fetch_to(cs, data.B); +} + +bool ChanState::cell_unpack(Ref cell_ref, ChanState::Record_chan_state_init& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanState::unpack(vm::CellSlice& cs, ChanState::Record_chan_state_close& data) const { + return cs.fetch_ulong(3) == 1 + && cs.fetch_bool_to(data.signed_A) + && cs.fetch_bool_to(data.signed_B) + && t_Grams.fetch_to(cs, data.promise_A) + && t_Grams.fetch_to(cs, data.promise_B) + && cs.fetch_uint_to(32, data.expire_at) + && t_Grams.fetch_to(cs, data.A) + && t_Grams.fetch_to(cs, data.B); +} + +bool ChanState::cell_unpack(Ref cell_ref, ChanState::Record_chan_state_close& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanState::unpack(vm::CellSlice& cs, ChanState::Record_chan_state_payout& data) const { + return cs.fetch_ulong(3) == 2 + && t_Grams.fetch_to(cs, data.A) + && t_Grams.fetch_to(cs, data.B); +} + +bool ChanState::unpack_chan_state_payout(vm::CellSlice& cs, Ref& A, Ref& B) const { + return cs.fetch_ulong(3) == 2 + && t_Grams.fetch_to(cs, A) + && t_Grams.fetch_to(cs, B); +} + +bool ChanState::cell_unpack(Ref cell_ref, ChanState::Record_chan_state_payout& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanState::cell_unpack_chan_state_payout(Ref cell_ref, Ref& A, Ref& B) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack_chan_state_payout(cs, A, B) && cs.empty_ext(); +} + +bool ChanState::pack(vm::CellBuilder& cb, const ChanState::Record_chan_state_init& data) const { + return cb.store_long_bool(0, 3) + && cb.store_ulong_rchk_bool(data.signed_A, 1) + && cb.store_ulong_rchk_bool(data.signed_B, 1) + && t_Grams.store_from(cb, data.min_A) + && t_Grams.store_from(cb, data.min_B) + && cb.store_ulong_rchk_bool(data.expire_at, 32) + && t_Grams.store_from(cb, data.A) + && t_Grams.store_from(cb, data.B); +} + +bool ChanState::cell_pack(Ref& cell_ref, const ChanState::Record_chan_state_init& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanState::pack(vm::CellBuilder& cb, const ChanState::Record_chan_state_close& data) const { + return cb.store_long_bool(1, 3) + && cb.store_ulong_rchk_bool(data.signed_A, 1) + && cb.store_ulong_rchk_bool(data.signed_B, 1) + && t_Grams.store_from(cb, data.promise_A) + && t_Grams.store_from(cb, data.promise_B) + && cb.store_ulong_rchk_bool(data.expire_at, 32) + && t_Grams.store_from(cb, data.A) + && t_Grams.store_from(cb, data.B); +} + +bool ChanState::cell_pack(Ref& cell_ref, const ChanState::Record_chan_state_close& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanState::pack(vm::CellBuilder& cb, const ChanState::Record_chan_state_payout& data) const { + return cb.store_long_bool(2, 3) + && t_Grams.store_from(cb, data.A) + && t_Grams.store_from(cb, data.B); +} + +bool ChanState::pack_chan_state_payout(vm::CellBuilder& cb, Ref A, Ref B) const { + return cb.store_long_bool(2, 3) + && t_Grams.store_from(cb, A) + && t_Grams.store_from(cb, B); +} + +bool ChanState::cell_pack(Ref& cell_ref, const ChanState::Record_chan_state_payout& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanState::cell_pack_chan_state_payout(Ref& cell_ref, Ref A, Ref B) const { + vm::CellBuilder cb; + return pack_chan_state_payout(cb, std::move(A), std::move(B)) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanState::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + switch (get_tag(cs)) { + case chan_state_init: + return cs.advance(3) + && pp.open("chan_state_init") + && pp.fetch_uint_field(cs, 1, "signed_A") + && pp.fetch_uint_field(cs, 1, "signed_B") + && pp.field("min_A") + && t_Grams.print_skip(pp, cs) + && pp.field("min_B") + && t_Grams.print_skip(pp, cs) + && pp.fetch_uint_field(cs, 32, "expire_at") + && pp.field("A") + && t_Grams.print_skip(pp, cs) + && pp.field("B") + && t_Grams.print_skip(pp, cs) + && pp.close(); + case chan_state_close: + return cs.advance(3) + && pp.open("chan_state_close") + && pp.fetch_uint_field(cs, 1, "signed_A") + && pp.fetch_uint_field(cs, 1, "signed_B") + && pp.field("promise_A") + && t_Grams.print_skip(pp, cs) + && pp.field("promise_B") + && t_Grams.print_skip(pp, cs) + && pp.fetch_uint_field(cs, 32, "expire_at") + && pp.field("A") + && t_Grams.print_skip(pp, cs) + && pp.field("B") + && t_Grams.print_skip(pp, cs) + && pp.close(); + case chan_state_payout: + return cs.fetch_ulong(3) == 2 + && pp.open("chan_state_payout") + && pp.field("A") + && t_Grams.print_skip(pp, cs) + && pp.field("B") + && t_Grams.print_skip(pp, cs) + && pp.close(); + } + return pp.fail("unknown constructor for ChanState"); +} + +const ChanState t_ChanState; + +// +// code for type `ChanPromise` +// + +int ChanPromise::check_tag(const vm::CellSlice& cs) const { + return chan_promise; +} + +bool ChanPromise::skip(vm::CellSlice& cs) const { + return cs.advance(64) + && t_Grams.skip(cs) + && t_Grams.skip(cs); +} + +bool ChanPromise::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + return cs.advance(64) + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak); +} + +bool ChanPromise::unpack(vm::CellSlice& cs, ChanPromise::Record& data) const { + return cs.fetch_uint_to(64, data.channel_id) + && t_Grams.fetch_to(cs, data.promise_A) + && t_Grams.fetch_to(cs, data.promise_B); +} + +bool ChanPromise::unpack_chan_promise(vm::CellSlice& cs, unsigned long long& channel_id, Ref& promise_A, Ref& promise_B) const { + return cs.fetch_uint_to(64, channel_id) + && t_Grams.fetch_to(cs, promise_A) + && t_Grams.fetch_to(cs, promise_B); +} + +bool ChanPromise::cell_unpack(Ref cell_ref, ChanPromise::Record& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanPromise::cell_unpack_chan_promise(Ref cell_ref, unsigned long long& channel_id, Ref& promise_A, Ref& promise_B) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack_chan_promise(cs, channel_id, promise_A, promise_B) && cs.empty_ext(); +} + +bool ChanPromise::pack(vm::CellBuilder& cb, const ChanPromise::Record& data) const { + return cb.store_ulong_rchk_bool(data.channel_id, 64) + && t_Grams.store_from(cb, data.promise_A) + && t_Grams.store_from(cb, data.promise_B); +} + +bool ChanPromise::pack_chan_promise(vm::CellBuilder& cb, unsigned long long channel_id, Ref promise_A, Ref promise_B) const { + return cb.store_ulong_rchk_bool(channel_id, 64) + && t_Grams.store_from(cb, promise_A) + && t_Grams.store_from(cb, promise_B); +} + +bool ChanPromise::cell_pack(Ref& cell_ref, const ChanPromise::Record& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanPromise::cell_pack_chan_promise(Ref& cell_ref, unsigned long long channel_id, Ref promise_A, Ref promise_B) const { + vm::CellBuilder cb; + return pack_chan_promise(cb, channel_id, std::move(promise_A), std::move(promise_B)) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanPromise::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + return pp.open("chan_promise") + && pp.fetch_uint_field(cs, 64, "channel_id") + && pp.field("promise_A") + && t_Grams.print_skip(pp, cs) + && pp.field("promise_B") + && t_Grams.print_skip(pp, cs) + && pp.close(); +} + +const ChanPromise t_ChanPromise; + +// +// code for type `ChanSignedPromise` +// + +int ChanSignedPromise::check_tag(const vm::CellSlice& cs) const { + return chan_signed_promise; +} + +bool ChanSignedPromise::skip(vm::CellSlice& cs) const { + return t_Maybe_Ref_bits512.skip(cs) + && t_ChanPromise.skip(cs); +} + +bool ChanSignedPromise::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + return t_Maybe_Ref_bits512.validate_skip(ops, cs, weak) + && t_ChanPromise.validate_skip(ops, cs, weak); +} + +bool ChanSignedPromise::unpack(vm::CellSlice& cs, ChanSignedPromise::Record& data) const { + return t_Maybe_Ref_bits512.fetch_to(cs, data.sig) + && t_ChanPromise.fetch_to(cs, data.promise); +} + +bool ChanSignedPromise::unpack_chan_signed_promise(vm::CellSlice& cs, Ref& sig, Ref& promise) const { + return t_Maybe_Ref_bits512.fetch_to(cs, sig) + && t_ChanPromise.fetch_to(cs, promise); +} + +bool ChanSignedPromise::cell_unpack(Ref cell_ref, ChanSignedPromise::Record& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanSignedPromise::cell_unpack_chan_signed_promise(Ref cell_ref, Ref& sig, Ref& promise) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack_chan_signed_promise(cs, sig, promise) && cs.empty_ext(); +} + +bool ChanSignedPromise::pack(vm::CellBuilder& cb, const ChanSignedPromise::Record& data) const { + return t_Maybe_Ref_bits512.store_from(cb, data.sig) + && t_ChanPromise.store_from(cb, data.promise); +} + +bool ChanSignedPromise::pack_chan_signed_promise(vm::CellBuilder& cb, Ref sig, Ref promise) const { + return t_Maybe_Ref_bits512.store_from(cb, sig) + && t_ChanPromise.store_from(cb, promise); +} + +bool ChanSignedPromise::cell_pack(Ref& cell_ref, const ChanSignedPromise::Record& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanSignedPromise::cell_pack_chan_signed_promise(Ref& cell_ref, Ref sig, Ref promise) const { + vm::CellBuilder cb; + return pack_chan_signed_promise(cb, std::move(sig), std::move(promise)) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanSignedPromise::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + return pp.open("chan_signed_promise") + && pp.field("sig") + && t_Maybe_Ref_bits512.print_skip(pp, cs) + && pp.field("promise") + && t_ChanPromise.print_skip(pp, cs) + && pp.close(); +} + +const ChanSignedPromise t_ChanSignedPromise; + +// +// code for type `ChanMsg` +// +constexpr unsigned ChanMsg::cons_tag[3]; + +int ChanMsg::check_tag(const vm::CellSlice& cs) const { + switch (get_tag(cs)) { + case chan_msg_init: + return cs.prefetch_ulong(32) == 0x27317822 ? chan_msg_init : -1; + case chan_msg_close: + return cs.prefetch_ulong(32) == 0xf28ae183U ? chan_msg_close : -1; + case chan_msg_timeout: + return cs.prefetch_ulong(32) == 0x43278a28 ? chan_msg_timeout : -1; + } + return -1; +} + +bool ChanMsg::skip(vm::CellSlice& cs) const { + switch (get_tag(cs)) { + case chan_msg_init: + return cs.advance(32) + && t_Grams.skip(cs) + && t_Grams.skip(cs) + && t_Grams.skip(cs) + && t_Grams.skip(cs) + && cs.advance(64); + case chan_msg_close: + return cs.advance(32) + && t_Grams.skip(cs) + && t_Grams.skip(cs) + && t_ChanSignedPromise.skip(cs); + case chan_msg_timeout: + return cs.advance(32); + } + return false; +} + +bool ChanMsg::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + switch (get_tag(cs)) { + case chan_msg_init: + return cs.fetch_ulong(32) == 0x27317822 + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak) + && cs.advance(64); + case chan_msg_close: + return cs.fetch_ulong(32) == 0xf28ae183U + && t_Grams.validate_skip(ops, cs, weak) + && t_Grams.validate_skip(ops, cs, weak) + && t_ChanSignedPromise.validate_skip(ops, cs, weak); + case chan_msg_timeout: + return cs.fetch_ulong(32) == 0x43278a28; + } + return false; +} + +bool ChanMsg::unpack(vm::CellSlice& cs, ChanMsg::Record_chan_msg_init& data) const { + return cs.fetch_ulong(32) == 0x27317822 + && t_Grams.fetch_to(cs, data.inc_A) + && t_Grams.fetch_to(cs, data.inc_B) + && t_Grams.fetch_to(cs, data.min_A) + && t_Grams.fetch_to(cs, data.min_B) + && cs.fetch_uint_to(64, data.channel_id); +} + +bool ChanMsg::cell_unpack(Ref cell_ref, ChanMsg::Record_chan_msg_init& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanMsg::unpack(vm::CellSlice& cs, ChanMsg::Record_chan_msg_close& data) const { + return cs.fetch_ulong(32) == 0xf28ae183U + && t_Grams.fetch_to(cs, data.extra_A) + && t_Grams.fetch_to(cs, data.extra_B) + && t_ChanSignedPromise.fetch_to(cs, data.promise); +} + +bool ChanMsg::unpack_chan_msg_close(vm::CellSlice& cs, Ref& extra_A, Ref& extra_B, Ref& promise) const { + return cs.fetch_ulong(32) == 0xf28ae183U + && t_Grams.fetch_to(cs, extra_A) + && t_Grams.fetch_to(cs, extra_B) + && t_ChanSignedPromise.fetch_to(cs, promise); +} + +bool ChanMsg::cell_unpack(Ref cell_ref, ChanMsg::Record_chan_msg_close& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanMsg::cell_unpack_chan_msg_close(Ref cell_ref, Ref& extra_A, Ref& extra_B, Ref& promise) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack_chan_msg_close(cs, extra_A, extra_B, promise) && cs.empty_ext(); +} + +bool ChanMsg::unpack(vm::CellSlice& cs, ChanMsg::Record_chan_msg_timeout& data) const { + return cs.fetch_ulong(32) == 0x43278a28; +} + +bool ChanMsg::unpack_chan_msg_timeout(vm::CellSlice& cs) const { + return cs.fetch_ulong(32) == 0x43278a28; +} + +bool ChanMsg::cell_unpack(Ref cell_ref, ChanMsg::Record_chan_msg_timeout& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanMsg::cell_unpack_chan_msg_timeout(Ref cell_ref) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack_chan_msg_timeout(cs) && cs.empty_ext(); +} + +bool ChanMsg::pack(vm::CellBuilder& cb, const ChanMsg::Record_chan_msg_init& data) const { + return cb.store_long_bool(0x27317822, 32) + && t_Grams.store_from(cb, data.inc_A) + && t_Grams.store_from(cb, data.inc_B) + && t_Grams.store_from(cb, data.min_A) + && t_Grams.store_from(cb, data.min_B) + && cb.store_ulong_rchk_bool(data.channel_id, 64); +} + +bool ChanMsg::cell_pack(Ref& cell_ref, const ChanMsg::Record_chan_msg_init& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanMsg::pack(vm::CellBuilder& cb, const ChanMsg::Record_chan_msg_close& data) const { + return cb.store_long_bool(0xf28ae183U, 32) + && t_Grams.store_from(cb, data.extra_A) + && t_Grams.store_from(cb, data.extra_B) + && t_ChanSignedPromise.store_from(cb, data.promise); +} + +bool ChanMsg::pack_chan_msg_close(vm::CellBuilder& cb, Ref extra_A, Ref extra_B, Ref promise) const { + return cb.store_long_bool(0xf28ae183U, 32) + && t_Grams.store_from(cb, extra_A) + && t_Grams.store_from(cb, extra_B) + && t_ChanSignedPromise.store_from(cb, promise); +} + +bool ChanMsg::cell_pack(Ref& cell_ref, const ChanMsg::Record_chan_msg_close& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanMsg::cell_pack_chan_msg_close(Ref& cell_ref, Ref extra_A, Ref extra_B, Ref promise) const { + vm::CellBuilder cb; + return pack_chan_msg_close(cb, std::move(extra_A), std::move(extra_B), std::move(promise)) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanMsg::pack(vm::CellBuilder& cb, const ChanMsg::Record_chan_msg_timeout& data) const { + return cb.store_long_bool(0x43278a28, 32); +} + +bool ChanMsg::pack_chan_msg_timeout(vm::CellBuilder& cb) const { + return cb.store_long_bool(0x43278a28, 32); +} + +bool ChanMsg::cell_pack(Ref& cell_ref, const ChanMsg::Record_chan_msg_timeout& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanMsg::cell_pack_chan_msg_timeout(Ref& cell_ref) const { + vm::CellBuilder cb; + return pack_chan_msg_timeout(cb) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanMsg::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + switch (get_tag(cs)) { + case chan_msg_init: + return cs.fetch_ulong(32) == 0x27317822 + && pp.open("chan_msg_init") + && pp.field("inc_A") + && t_Grams.print_skip(pp, cs) + && pp.field("inc_B") + && t_Grams.print_skip(pp, cs) + && pp.field("min_A") + && t_Grams.print_skip(pp, cs) + && pp.field("min_B") + && t_Grams.print_skip(pp, cs) + && pp.fetch_uint_field(cs, 64, "channel_id") + && pp.close(); + case chan_msg_close: + return cs.fetch_ulong(32) == 0xf28ae183U + && pp.open("chan_msg_close") + && pp.field("extra_A") + && t_Grams.print_skip(pp, cs) + && pp.field("extra_B") + && t_Grams.print_skip(pp, cs) + && pp.field("promise") + && t_ChanSignedPromise.print_skip(pp, cs) + && pp.close(); + case chan_msg_timeout: + return cs.fetch_ulong(32) == 0x43278a28 + && pp.cons("chan_msg_timeout"); + } + return pp.fail("unknown constructor for ChanMsg"); +} + +const ChanMsg t_ChanMsg; + +// +// code for type `ChanSignedMsg` +// + +int ChanSignedMsg::check_tag(const vm::CellSlice& cs) const { + return chan_signed_msg; +} + +bool ChanSignedMsg::skip(vm::CellSlice& cs) const { + return t_Maybe_Ref_bits512.skip(cs) + && t_Maybe_Ref_bits512.skip(cs) + && t_ChanMsg.skip(cs); +} + +bool ChanSignedMsg::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + return t_Maybe_Ref_bits512.validate_skip(ops, cs, weak) + && t_Maybe_Ref_bits512.validate_skip(ops, cs, weak) + && t_ChanMsg.validate_skip(ops, cs, weak); +} + +bool ChanSignedMsg::unpack(vm::CellSlice& cs, ChanSignedMsg::Record& data) const { + return t_Maybe_Ref_bits512.fetch_to(cs, data.sig_A) + && t_Maybe_Ref_bits512.fetch_to(cs, data.sig_B) + && t_ChanMsg.fetch_to(cs, data.msg); +} + +bool ChanSignedMsg::unpack_chan_signed_msg(vm::CellSlice& cs, Ref& sig_A, Ref& sig_B, Ref& msg) const { + return t_Maybe_Ref_bits512.fetch_to(cs, sig_A) + && t_Maybe_Ref_bits512.fetch_to(cs, sig_B) + && t_ChanMsg.fetch_to(cs, msg); +} + +bool ChanSignedMsg::cell_unpack(Ref cell_ref, ChanSignedMsg::Record& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanSignedMsg::cell_unpack_chan_signed_msg(Ref cell_ref, Ref& sig_A, Ref& sig_B, Ref& msg) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack_chan_signed_msg(cs, sig_A, sig_B, msg) && cs.empty_ext(); +} + +bool ChanSignedMsg::pack(vm::CellBuilder& cb, const ChanSignedMsg::Record& data) const { + return t_Maybe_Ref_bits512.store_from(cb, data.sig_A) + && t_Maybe_Ref_bits512.store_from(cb, data.sig_B) + && t_ChanMsg.store_from(cb, data.msg); +} + +bool ChanSignedMsg::pack_chan_signed_msg(vm::CellBuilder& cb, Ref sig_A, Ref sig_B, Ref msg) const { + return t_Maybe_Ref_bits512.store_from(cb, sig_A) + && t_Maybe_Ref_bits512.store_from(cb, sig_B) + && t_ChanMsg.store_from(cb, msg); +} + +bool ChanSignedMsg::cell_pack(Ref& cell_ref, const ChanSignedMsg::Record& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanSignedMsg::cell_pack_chan_signed_msg(Ref& cell_ref, Ref sig_A, Ref sig_B, Ref msg) const { + vm::CellBuilder cb; + return pack_chan_signed_msg(cb, std::move(sig_A), std::move(sig_B), std::move(msg)) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanSignedMsg::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + return pp.open("chan_signed_msg") + && pp.field("sig_A") + && t_Maybe_Ref_bits512.print_skip(pp, cs) + && pp.field("sig_B") + && t_Maybe_Ref_bits512.print_skip(pp, cs) + && pp.field("msg") + && t_ChanMsg.print_skip(pp, cs) + && pp.close(); +} + +const ChanSignedMsg t_ChanSignedMsg; + +// +// code for type `ChanData` +// + +int ChanData::check_tag(const vm::CellSlice& cs) const { + return chan_data; +} + +bool ChanData::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { + return t_ChanConfig.validate_skip_ref(ops, cs, weak) + && t_ChanState.validate_skip_ref(ops, cs, weak); +} + +bool ChanData::unpack(vm::CellSlice& cs, ChanData::Record& data) const { + return cs.fetch_ref_to(data.config) + && cs.fetch_ref_to(data.state); +} + +bool ChanData::unpack_chan_data(vm::CellSlice& cs, Ref& config, Ref& state) const { + return cs.fetch_ref_to(config) + && cs.fetch_ref_to(state); +} + +bool ChanData::cell_unpack(Ref cell_ref, ChanData::Record& data) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack(cs, data) && cs.empty_ext(); +} + +bool ChanData::cell_unpack_chan_data(Ref cell_ref, Ref& config, Ref& state) const { + if (cell_ref.is_null()) { return false; } + auto cs = load_cell_slice(std::move(cell_ref)); + return unpack_chan_data(cs, config, state) && cs.empty_ext(); +} + +bool ChanData::pack(vm::CellBuilder& cb, const ChanData::Record& data) const { + return cb.store_ref_bool(data.config) + && cb.store_ref_bool(data.state); +} + +bool ChanData::pack_chan_data(vm::CellBuilder& cb, Ref config, Ref state) const { + return cb.store_ref_bool(config) + && cb.store_ref_bool(state); +} + +bool ChanData::cell_pack(Ref& cell_ref, const ChanData::Record& data) const { + vm::CellBuilder cb; + return pack(cb, data) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanData::cell_pack_chan_data(Ref& cell_ref, Ref config, Ref state) const { + vm::CellBuilder cb; + return pack_chan_data(cb, std::move(config), std::move(state)) && std::move(cb).finalize_to(cell_ref); +} + +bool ChanData::print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const { + return pp.open("chan_data") + && pp.field("config") + && t_ChanConfig.print_ref(pp, cs.fetch_ref()) + && pp.field("state") + && t_ChanState.print_ref(pp, cs.fetch_ref()) + && pp.close(); +} + +const ChanData t_ChanData; + +// definitions of constant types used + +const NatWidth t_natwidth_1{1}; +const NatWidth t_natwidth_9{9}; +const NatLeq t_natleq_30{30}; +const Maybe t_Maybe_Anycast{t_Anycast}; +const Int t_int8{8}; +const Bits t_bits256{256}; +const Int t_int32{32}; +const VarUInteger t_VarUInteger_16{16}; +const VarUInteger t_VarUInteger_32{32}; +const HashmapE t_HashmapE_32_VarUInteger_32{32, t_VarUInteger_32}; +const UInt t_uint64{64}; +const UInt t_uint32{32}; +const NatWidth t_natwidth_5{5}; +const Maybe t_Maybe_natwidth_5{t_natwidth_5}; +const Maybe t_Maybe_TickTock{t_TickTock}; +const Maybe t_Maybe_Ref_Cell{t_RefCell}; +const HashmapE t_HashmapE_256_SimpleLib{256, t_SimpleLib}; +const RefT t_Ref_StateInit{t_StateInit}; +const Either t_Either_StateInit_Ref_StateInit{t_StateInit, t_Ref_StateInit}; +const Maybe t_Maybe_Either_StateInit_Ref_StateInit{t_Either_StateInit_Ref_StateInit}; +const Message t_Message_Any{t_Anything}; +const NatLeq t_natleq_96{96}; +const RefT t_Ref_Message_Any{t_Message_Any}; +const RefT t_Ref_Transaction{t_Transaction}; +const RefT t_Ref_MsgEnvelope{t_MsgEnvelope}; +const HashmapAugE t_HashmapAugE_256_InMsg_ImportFees{256, t_InMsg, t_ImportFees}; +const RefT t_Ref_InMsg{t_InMsg}; +const UInt t_uint63{63}; +const HashmapAugE t_HashmapAugE_256_OutMsg_CurrencyCollection{256, t_OutMsg, t_CurrencyCollection}; +const HashmapAugE t_HashmapAugE_352_EnqueuedMsg_uint64{352, t_EnqueuedMsg, t_uint64}; +const HashmapE t_HashmapE_96_ProcessedUpto{96, t_ProcessedUpto}; +const HashmapE t_HashmapE_320_IhrPendingSince{320, t_IhrPendingSince}; +const VarUInteger t_VarUInteger_7{7}; +const Maybe t_Maybe_Grams{t_Grams}; +const RefT t_Ref_Account{t_Account}; +const HashmapAugE t_HashmapAugE_256_ShardAccount_DepthBalanceInfo{256, t_ShardAccount, t_DepthBalanceInfo}; +const UInt t_uint15{15}; +const Maybe t_Maybe_Ref_Message_Any{t_Ref_Message_Any}; +const HashmapE t_HashmapE_15_Ref_Message_Any{15, t_Ref_Message_Any}; +const RefT t_Ref_TYPE_1614{t_Transaction_aux}; +const HASH_UPDATE t_HASH_UPDATE_Account{t_Account}; +const RefT t_Ref_HASH_UPDATE_Account{t_HASH_UPDATE_Account}; +const RefT t_Ref_TransactionDescr{t_TransactionDescr}; +const UInt t_uint16{16}; +const HashmapAug t_HashmapAug_64_Ref_Transaction_CurrencyCollection{64, t_Ref_Transaction, t_CurrencyCollection}; +const HashmapAugE t_HashmapAugE_256_AccountBlock_CurrencyCollection{256, t_AccountBlock, t_CurrencyCollection}; +const VarUInteger t_VarUInteger_3{3}; +const Maybe t_Maybe_VarUInteger_3{t_VarUInteger_3}; +const Maybe t_Maybe_int32{t_int32}; +const RefT t_Ref_TYPE_1626{t_TrComputePhase_aux}; const Maybe t_Maybe_TrStoragePhase{t_TrStoragePhase}; const Maybe t_Maybe_TrCreditPhase{t_TrCreditPhase}; const RefT t_Ref_TrActionPhase{t_TrActionPhase}; @@ -22403,7 +23419,7 @@ const RefT t_Ref_OutMsgQueueInfo{t_OutMsgQueueInfo}; const RefT t_Ref_ShardAccounts{t_ShardAccounts}; const HashmapE t_HashmapE_256_LibDescr{256, t_LibDescr}; const Maybe t_Maybe_BlkMasterInfo{t_BlkMasterInfo}; -const RefT t_Ref_TYPE_1639{t_ShardStateUnsplit_aux}; +const RefT t_Ref_TYPE_1640{t_ShardStateUnsplit_aux}; const RefT t_Ref_McStateExtra{t_McStateExtra}; const Maybe t_Maybe_Ref_McStateExtra{t_Ref_McStateExtra}; const RefT t_Ref_ShardStateUnsplit{t_ShardStateUnsplit}; @@ -22422,10 +23438,10 @@ const RefT t_Ref_OutMsgDescr{t_OutMsgDescr}; const RefT t_Ref_ShardAccountBlocks{t_ShardAccountBlocks}; const RefT t_Ref_McBlockExtra{t_McBlockExtra}; const Maybe t_Maybe_Ref_McBlockExtra{t_Ref_McBlockExtra}; -const RefT t_Ref_TYPE_1650{t_ValueFlow_aux}; -const RefT t_Ref_TYPE_1651{t_ValueFlow_aux1}; +const RefT t_Ref_TYPE_1651{t_ValueFlow_aux}; +const RefT t_Ref_TYPE_1652{t_ValueFlow_aux1}; const NatWidth t_natwidth_3{3}; -const RefT t_Ref_TYPE_1655{t_ShardDescr_aux}; +const RefT t_Ref_TYPE_1656{t_ShardDescr_aux}; const BinTree t_BinTree_ShardDescr{t_ShardDescr}; const RefT t_Ref_BinTree_ShardDescr{t_BinTree_ShardDescr}; const HashmapE t_HashmapE_32_Ref_BinTree_ShardDescr{32, t_Ref_BinTree_ShardDescr}; @@ -22437,11 +23453,11 @@ const HashmapE t_HashmapE_256_CreatorStats{256, t_CreatorStats}; const HashmapAugE t_HashmapAugE_256_CreatorStats_uint32{256, t_CreatorStats, t_uint32}; const NatWidth t_natwidth_16{16}; const Maybe t_Maybe_ExtBlkRef{t_ExtBlkRef}; -const RefT t_Ref_TYPE_1669{t_McStateExtra_aux}; +const RefT t_Ref_TYPE_1670{t_McStateExtra_aux}; const RefT t_Ref_SignedCertificate{t_SignedCertificate}; const HashmapE t_HashmapE_16_CryptoSignaturePair{16, t_CryptoSignaturePair}; const Maybe t_Maybe_Ref_InMsg{t_Ref_InMsg}; -const RefT t_Ref_TYPE_1677{t_McBlockExtra_aux}; +const RefT t_Ref_TYPE_1678{t_McBlockExtra_aux}; const Hashmap t_Hashmap_16_ValidatorDescr{16, t_ValidatorDescr}; const HashmapE t_HashmapE_16_ValidatorDescr{16, t_ValidatorDescr}; const Hashmap t_Hashmap_32_True{32, t_True}; @@ -22464,6 +23480,11 @@ const RefT t_Ref_BlockSignatures{t_BlockSignatures}; const Maybe t_Maybe_Ref_BlockSignatures{t_Ref_BlockSignatures}; const RefT t_Ref_TopBlockDescr{t_TopBlockDescr}; const HashmapE t_HashmapE_96_Ref_TopBlockDescr{96, t_Ref_TopBlockDescr}; +const MERKLE_PROOF t_MERKLE_PROOF_Block{t_Block}; +const RefT t_Ref_MERKLE_PROOF_Block{t_MERKLE_PROOF_Block}; +const MERKLE_PROOF t_MERKLE_PROOF_ShardState{t_ShardState}; +const RefT t_Ref_MERKLE_PROOF_ShardState{t_MERKLE_PROOF_ShardState}; +const RefT t_Ref_ProducerInfo{t_ProducerInfo}; const RefT t_Ref_ComplaintDescr{t_ComplaintDescr}; const RefT t_Ref_ValidatorComplaint{t_ValidatorComplaint}; const Int t_int257{257}; @@ -22472,7 +23493,7 @@ const NatLeq t_natleq_4{4}; const RefT t_Ref_VmStackValue{t_VmStackValue}; const NatWidth t_natwidth_24{24}; const HashmapE t_HashmapE_4_VmStackValue{4, t_VmStackValue}; -const RefT t_Ref_TYPE_1715{t_VmGasLimits_aux}; +const RefT t_Ref_TYPE_1717{t_VmGasLimits_aux}; const HashmapE t_HashmapE_256_Ref_Cell{256, t_RefCell}; const UInt t_uint13{13}; const Maybe t_Maybe_uint13{t_uint13}; @@ -22482,6 +23503,12 @@ const Maybe t_Maybe_int16{t_int16}; const RefT t_Ref_VmCont{t_VmCont}; const RefT t_Ref_DNSRecord{t_DNSRecord}; const HashmapE t_HashmapE_16_Ref_DNSRecord{16, t_Ref_DNSRecord}; +const RefT t_Ref_MsgAddressInt{t_MsgAddressInt}; +const Bits t_bits512{512}; +const RefT t_Ref_bits512{t_bits512}; +const Maybe t_Maybe_Ref_bits512{t_Ref_bits512}; +const RefT t_Ref_ChanConfig{t_ChanConfig}; +const RefT t_Ref_ChanState{t_ChanState}; // definition of type name registration function bool register_simple_types(std::function func) { @@ -22603,6 +23630,7 @@ bool register_simple_types(std::function func) { && func("BlockProof", &t_BlockProof) && func("TopBlockDescr", &t_TopBlockDescr) && func("TopBlockDescrSet", &t_TopBlockDescrSet) + && func("ProducerInfo", &t_ProducerInfo) && func("ComplaintDescr", &t_ComplaintDescr) && func("ValidatorComplaint", &t_ValidatorComplaint) && func("ValidatorComplaintStatus", &t_ValidatorComplaintStatus) @@ -22620,7 +23648,14 @@ bool register_simple_types(std::function func) { && func("ProtoList", &t_ProtoList) && func("Protocol", &t_Protocol) && func("SmcCapList", &t_SmcCapList) - && func("SmcCapability", &t_SmcCapability); + && func("SmcCapability", &t_SmcCapability) + && func("ChanConfig", &t_ChanConfig) + && func("ChanState", &t_ChanState) + && func("ChanPromise", &t_ChanPromise) + && func("ChanSignedPromise", &t_ChanSignedPromise) + && func("ChanMsg", &t_ChanMsg) + && func("ChanSignedMsg", &t_ChanSignedMsg) + && func("ChanData", &t_ChanData); } diff --git a/submodules/ton/tonlib-src/crypto/block/block-auto.h b/submodules/ton/tonlib-src/crypto/block/block-auto.h index 14f421843a7..f1a1984ba04 100644 --- a/submodules/ton/tonlib-src/crypto/block/block-auto.h +++ b/submodules/ton/tonlib-src/crypto/block/block-auto.h @@ -28,6 +28,7 @@ // uses built-in type `uint256` // uses built-in type `int257` // uses built-in type `bits256` +// uses built-in type `bits512` namespace block { @@ -3284,6 +3285,54 @@ struct HASH_UPDATE final : TLB_Complex { } }; +// +// headers for type `MERKLE_PROOF` +// + +struct MERKLE_PROOF final : TLB_Complex { + enum { _merkle_proof }; + static constexpr int cons_len_exact = 8; + static constexpr unsigned char cons_tag[1] = { 3 }; + const TLB &X_; + MERKLE_PROOF(const TLB& X) : X_(X) {} + struct Record; + bool always_special() const override { + return true; + } + int get_size(const vm::CellSlice& cs) const override { + return 0x10118; + } + bool skip(vm::CellSlice& cs) const override { + return cs.advance_ext(0x10118); + } + bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; + bool unpack(vm::CellSlice& cs, Record& data) const; + bool unpack__merkle_proof(vm::CellSlice& cs, td::BitArray<256>& virtual_hash, int& depth, Ref& virtual_root) const; + bool cell_unpack(Ref cell_ref, Record& data) const; + bool cell_unpack__merkle_proof(Ref cell_ref, td::BitArray<256>& virtual_hash, int& depth, Ref& virtual_root) const; + bool pack(vm::CellBuilder& cb, const Record& data) const; + bool pack__merkle_proof(vm::CellBuilder& cb, td::BitArray<256> virtual_hash, int depth, Ref virtual_root) const; + bool cell_pack(Ref& cell_ref, const Record& data) const; + bool cell_pack__merkle_proof(Ref& cell_ref, td::BitArray<256> virtual_hash, int depth, Ref virtual_root) const; + bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; + std::ostream& print_type(std::ostream& os) const override { + return os << "(MERKLE_PROOF " << X_ << ")"; + } + int check_tag(const vm::CellSlice& cs) const override; + int get_tag(const vm::CellSlice& cs) const override { + return 0; + } +}; + +struct MERKLE_PROOF::Record { + typedef MERKLE_PROOF type_class; + td::BitArray<256> virtual_hash; // virtual_hash : bits256 + int depth; // depth : uint16 + Ref virtual_root; // virtual_root : ^X + Record() = default; + Record(const td::BitArray<256>& _virtual_hash, int _depth, Ref _virtual_root) : virtual_hash(_virtual_hash), depth(_depth), virtual_root(std::move(_virtual_root)) {} +}; + // // headers for type `AccountBlock` // @@ -7727,19 +7776,19 @@ struct TopBlockDescrSet final : TLB_Complex { extern const TopBlockDescrSet t_TopBlockDescrSet; // -// headers for type `ComplaintDescr` +// headers for type `ProducerInfo` // -struct ComplaintDescr final : TLB_Complex { - enum { no_blk_gen }; - static constexpr int cons_len_exact = 32; - static constexpr unsigned cons_tag[1] = { 0x7e545dda }; +struct ProducerInfo final : TLB_Complex { + enum { prod_info }; + static constexpr int cons_len_exact = 8; + static constexpr unsigned char cons_tag[1] = { 0x34 }; struct Record; int get_size(const vm::CellSlice& cs) const override { - return 0x202c0; + return 0x20288; } bool skip(vm::CellSlice& cs) const override { - return cs.advance_ext(0x202c0); + return cs.advance_ext(0x20288); } bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; bool unpack(vm::CellSlice& cs, Record& data) const; @@ -7748,7 +7797,7 @@ struct ComplaintDescr final : TLB_Complex { bool cell_pack(Ref& cell_ref, const Record& data) const; bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; std::ostream& print_type(std::ostream& os) const override { - return os << "ComplaintDescr"; + return os << "ProducerInfo"; } int check_tag(const vm::CellSlice& cs) const override; int get_tag(const vm::CellSlice& cs) const override { @@ -7756,15 +7805,66 @@ struct ComplaintDescr final : TLB_Complex { } }; -struct ComplaintDescr::Record { - typedef ComplaintDescr type_class; +struct ProducerInfo::Record { + typedef ProducerInfo type_class; + unsigned utime; // utime : uint32 Ref mc_blk_ref; // mc_blk_ref : ExtBlkRef - unsigned from_utime; // from_utime : uint32 - unsigned to_utime; // to_utime : uint32 - Ref state_proof; // state_proof : ^Cell - Ref prod_proof; // prod_proof : ^Cell + Ref state_proof; // state_proof : ^(MERKLE_PROOF Block) + Ref prod_proof; // prod_proof : ^(MERKLE_PROOF ShardState) Record() = default; - Record(Ref _mc_blk_ref, unsigned _from_utime, unsigned _to_utime, Ref _state_proof, Ref _prod_proof) : mc_blk_ref(std::move(_mc_blk_ref)), from_utime(_from_utime), to_utime(_to_utime), state_proof(std::move(_state_proof)), prod_proof(std::move(_prod_proof)) {} + Record(unsigned _utime, Ref _mc_blk_ref, Ref _state_proof, Ref _prod_proof) : utime(_utime), mc_blk_ref(std::move(_mc_blk_ref)), state_proof(std::move(_state_proof)), prod_proof(std::move(_prod_proof)) {} +}; + +extern const ProducerInfo t_ProducerInfo; + +// +// headers for type `ComplaintDescr` +// + +struct ComplaintDescr final : TLB_Complex { + enum { no_blk_gen, no_blk_gen_diff }; + static constexpr int cons_len_exact = 32; + static constexpr unsigned cons_tag[2] = { 0x450e8bd9, 0xc737b0caU }; + struct Record_no_blk_gen { + typedef ComplaintDescr type_class; + unsigned from_utime; // from_utime : uint32 + Ref prod_info; // prod_info : ^ProducerInfo + Record_no_blk_gen() = default; + Record_no_blk_gen(unsigned _from_utime, Ref _prod_info) : from_utime(_from_utime), prod_info(std::move(_prod_info)) {} + }; + struct Record_no_blk_gen_diff { + typedef ComplaintDescr type_class; + Ref prod_info_old; // prod_info_old : ^ProducerInfo + Ref prod_info_new; // prod_info_new : ^ProducerInfo + Record_no_blk_gen_diff() = default; + Record_no_blk_gen_diff(Ref _prod_info_old, Ref _prod_info_new) : prod_info_old(std::move(_prod_info_old)), prod_info_new(std::move(_prod_info_new)) {} + }; + bool skip(vm::CellSlice& cs) const override; + bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; + bool unpack(vm::CellSlice& cs, Record_no_blk_gen& data) const; + bool unpack_no_blk_gen(vm::CellSlice& cs, unsigned& from_utime, Ref& prod_info) const; + bool cell_unpack(Ref cell_ref, Record_no_blk_gen& data) const; + bool cell_unpack_no_blk_gen(Ref cell_ref, unsigned& from_utime, Ref& prod_info) const; + bool pack(vm::CellBuilder& cb, const Record_no_blk_gen& data) const; + bool pack_no_blk_gen(vm::CellBuilder& cb, unsigned from_utime, Ref prod_info) const; + bool cell_pack(Ref& cell_ref, const Record_no_blk_gen& data) const; + bool cell_pack_no_blk_gen(Ref& cell_ref, unsigned from_utime, Ref prod_info) const; + bool unpack(vm::CellSlice& cs, Record_no_blk_gen_diff& data) const; + bool unpack_no_blk_gen_diff(vm::CellSlice& cs, Ref& prod_info_old, Ref& prod_info_new) const; + bool cell_unpack(Ref cell_ref, Record_no_blk_gen_diff& data) const; + bool cell_unpack_no_blk_gen_diff(Ref cell_ref, Ref& prod_info_old, Ref& prod_info_new) const; + bool pack(vm::CellBuilder& cb, const Record_no_blk_gen_diff& data) const; + bool pack_no_blk_gen_diff(vm::CellBuilder& cb, Ref prod_info_old, Ref prod_info_new) const; + bool cell_pack(Ref& cell_ref, const Record_no_blk_gen_diff& data) const; + bool cell_pack_no_blk_gen_diff(Ref& cell_ref, Ref prod_info_old, Ref prod_info_new) const; + bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; + std::ostream& print_type(std::ostream& os) const override { + return os << "ComplaintDescr"; + } + int check_tag(const vm::CellSlice& cs) const override; + int get_tag(const vm::CellSlice& cs) const override { + return (int)cs.prefetch_ulong(1); + } }; extern const ComplaintDescr t_ComplaintDescr; @@ -9035,6 +9135,344 @@ struct SmcCapability final : TLB_Complex { extern const SmcCapability t_SmcCapability; +// +// headers for type `ChanConfig` +// + +struct ChanConfig final : TLB_Complex { + enum { chan_config }; + static constexpr int cons_len_exact = 0; + struct Record; + int get_size(const vm::CellSlice& cs) const override { + return 0x20280; + } + bool skip(vm::CellSlice& cs) const override { + return cs.advance_ext(0x20280); + } + bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; + bool unpack(vm::CellSlice& cs, Record& data) const; + bool cell_unpack(Ref cell_ref, Record& data) const; + bool pack(vm::CellBuilder& cb, const Record& data) const; + bool cell_pack(Ref& cell_ref, const Record& data) const; + bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; + std::ostream& print_type(std::ostream& os) const override { + return os << "ChanConfig"; + } + int check_tag(const vm::CellSlice& cs) const override; + int get_tag(const vm::CellSlice& cs) const override { + return 0; + } +}; + +struct ChanConfig::Record { + typedef ChanConfig type_class; + unsigned init_timeout; // init_timeout : uint32 + unsigned close_timeout; // close_timeout : uint32 + td::BitArray<256> a_key; // a_key : bits256 + td::BitArray<256> b_key; // b_key : bits256 + Ref a_addr; // a_addr : ^MsgAddressInt + Ref b_addr; // b_addr : ^MsgAddressInt + unsigned long long channel_id; // channel_id : uint64 + Record() = default; + Record(unsigned _init_timeout, unsigned _close_timeout, const td::BitArray<256>& _a_key, const td::BitArray<256>& _b_key, Ref _a_addr, Ref _b_addr, unsigned long long _channel_id) : init_timeout(_init_timeout), close_timeout(_close_timeout), a_key(_a_key), b_key(_b_key), a_addr(std::move(_a_addr)), b_addr(std::move(_b_addr)), channel_id(_channel_id) {} +}; + +extern const ChanConfig t_ChanConfig; + +// +// headers for type `ChanState` +// + +struct ChanState final : TLB_Complex { + enum { chan_state_init, chan_state_close, chan_state_payout }; + static constexpr int cons_len_exact = 3; + struct Record_chan_state_init; + struct Record_chan_state_close; + struct Record_chan_state_payout { + typedef ChanState type_class; + Ref A; // A : Grams + Ref B; // B : Grams + Record_chan_state_payout() = default; + Record_chan_state_payout(Ref _A, Ref _B) : A(std::move(_A)), B(std::move(_B)) {} + }; + bool skip(vm::CellSlice& cs) const override; + bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; + bool unpack(vm::CellSlice& cs, Record_chan_state_init& data) const; + bool cell_unpack(Ref cell_ref, Record_chan_state_init& data) const; + bool pack(vm::CellBuilder& cb, const Record_chan_state_init& data) const; + bool cell_pack(Ref& cell_ref, const Record_chan_state_init& data) const; + bool unpack(vm::CellSlice& cs, Record_chan_state_close& data) const; + bool cell_unpack(Ref cell_ref, Record_chan_state_close& data) const; + bool pack(vm::CellBuilder& cb, const Record_chan_state_close& data) const; + bool cell_pack(Ref& cell_ref, const Record_chan_state_close& data) const; + bool unpack(vm::CellSlice& cs, Record_chan_state_payout& data) const; + bool unpack_chan_state_payout(vm::CellSlice& cs, Ref& A, Ref& B) const; + bool cell_unpack(Ref cell_ref, Record_chan_state_payout& data) const; + bool cell_unpack_chan_state_payout(Ref cell_ref, Ref& A, Ref& B) const; + bool pack(vm::CellBuilder& cb, const Record_chan_state_payout& data) const; + bool pack_chan_state_payout(vm::CellBuilder& cb, Ref A, Ref B) const; + bool cell_pack(Ref& cell_ref, const Record_chan_state_payout& data) const; + bool cell_pack_chan_state_payout(Ref& cell_ref, Ref A, Ref B) const; + bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; + std::ostream& print_type(std::ostream& os) const override { + return os << "ChanState"; + } + int check_tag(const vm::CellSlice& cs) const override; + int get_tag(const vm::CellSlice& cs) const override { + return cs.bselect(3, 7); + } +}; + +struct ChanState::Record_chan_state_init { + typedef ChanState type_class; + bool signed_A; // signed_A : Bool + bool signed_B; // signed_B : Bool + Ref min_A; // min_A : Grams + Ref min_B; // min_B : Grams + unsigned expire_at; // expire_at : uint32 + Ref A; // A : Grams + Ref B; // B : Grams + Record_chan_state_init() = default; + Record_chan_state_init(bool _signed_A, bool _signed_B, Ref _min_A, Ref _min_B, unsigned _expire_at, Ref _A, Ref _B) : signed_A(_signed_A), signed_B(_signed_B), min_A(std::move(_min_A)), min_B(std::move(_min_B)), expire_at(_expire_at), A(std::move(_A)), B(std::move(_B)) {} +}; + +struct ChanState::Record_chan_state_close { + typedef ChanState type_class; + bool signed_A; // signed_A : Bool + bool signed_B; // signed_B : Bool + Ref promise_A; // promise_A : Grams + Ref promise_B; // promise_B : Grams + unsigned expire_at; // expire_at : uint32 + Ref A; // A : Grams + Ref B; // B : Grams + Record_chan_state_close() = default; + Record_chan_state_close(bool _signed_A, bool _signed_B, Ref _promise_A, Ref _promise_B, unsigned _expire_at, Ref _A, Ref _B) : signed_A(_signed_A), signed_B(_signed_B), promise_A(std::move(_promise_A)), promise_B(std::move(_promise_B)), expire_at(_expire_at), A(std::move(_A)), B(std::move(_B)) {} +}; + +extern const ChanState t_ChanState; + +// +// headers for type `ChanPromise` +// + +struct ChanPromise final : TLB_Complex { + enum { chan_promise }; + static constexpr int cons_len_exact = 0; + struct Record; + bool skip(vm::CellSlice& cs) const override; + bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; + bool unpack(vm::CellSlice& cs, Record& data) const; + bool unpack_chan_promise(vm::CellSlice& cs, unsigned long long& channel_id, Ref& promise_A, Ref& promise_B) const; + bool cell_unpack(Ref cell_ref, Record& data) const; + bool cell_unpack_chan_promise(Ref cell_ref, unsigned long long& channel_id, Ref& promise_A, Ref& promise_B) const; + bool pack(vm::CellBuilder& cb, const Record& data) const; + bool pack_chan_promise(vm::CellBuilder& cb, unsigned long long channel_id, Ref promise_A, Ref promise_B) const; + bool cell_pack(Ref& cell_ref, const Record& data) const; + bool cell_pack_chan_promise(Ref& cell_ref, unsigned long long channel_id, Ref promise_A, Ref promise_B) const; + bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; + std::ostream& print_type(std::ostream& os) const override { + return os << "ChanPromise"; + } + int check_tag(const vm::CellSlice& cs) const override; + int get_tag(const vm::CellSlice& cs) const override { + return 0; + } +}; + +struct ChanPromise::Record { + typedef ChanPromise type_class; + unsigned long long channel_id; // channel_id : uint64 + Ref promise_A; // promise_A : Grams + Ref promise_B; // promise_B : Grams + Record() = default; + Record(unsigned long long _channel_id, Ref _promise_A, Ref _promise_B) : channel_id(_channel_id), promise_A(std::move(_promise_A)), promise_B(std::move(_promise_B)) {} +}; + +extern const ChanPromise t_ChanPromise; + +// +// headers for type `ChanSignedPromise` +// + +struct ChanSignedPromise final : TLB_Complex { + enum { chan_signed_promise }; + static constexpr int cons_len_exact = 0; + struct Record { + typedef ChanSignedPromise type_class; + Ref sig; // sig : Maybe ^bits512 + Ref promise; // promise : ChanPromise + Record() = default; + Record(Ref _sig, Ref _promise) : sig(std::move(_sig)), promise(std::move(_promise)) {} + }; + bool skip(vm::CellSlice& cs) const override; + bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; + bool unpack(vm::CellSlice& cs, Record& data) const; + bool unpack_chan_signed_promise(vm::CellSlice& cs, Ref& sig, Ref& promise) const; + bool cell_unpack(Ref cell_ref, Record& data) const; + bool cell_unpack_chan_signed_promise(Ref cell_ref, Ref& sig, Ref& promise) const; + bool pack(vm::CellBuilder& cb, const Record& data) const; + bool pack_chan_signed_promise(vm::CellBuilder& cb, Ref sig, Ref promise) const; + bool cell_pack(Ref& cell_ref, const Record& data) const; + bool cell_pack_chan_signed_promise(Ref& cell_ref, Ref sig, Ref promise) const; + bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; + std::ostream& print_type(std::ostream& os) const override { + return os << "ChanSignedPromise"; + } + int check_tag(const vm::CellSlice& cs) const override; + int get_tag(const vm::CellSlice& cs) const override { + return 0; + } +}; + +extern const ChanSignedPromise t_ChanSignedPromise; + +// +// headers for type `ChanMsg` +// + +struct ChanMsg final : TLB_Complex { + enum { chan_msg_init, chan_msg_timeout, chan_msg_close }; + static constexpr int cons_len_exact = 32; + static constexpr unsigned cons_tag[3] = { 0x27317822, 0x43278a28, 0xf28ae183U }; + struct Record_chan_msg_init; + struct Record_chan_msg_close; + struct Record_chan_msg_timeout { + typedef ChanMsg type_class; + }; + bool skip(vm::CellSlice& cs) const override; + bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; + bool unpack(vm::CellSlice& cs, Record_chan_msg_init& data) const; + bool cell_unpack(Ref cell_ref, Record_chan_msg_init& data) const; + bool pack(vm::CellBuilder& cb, const Record_chan_msg_init& data) const; + bool cell_pack(Ref& cell_ref, const Record_chan_msg_init& data) const; + bool unpack(vm::CellSlice& cs, Record_chan_msg_close& data) const; + bool unpack_chan_msg_close(vm::CellSlice& cs, Ref& extra_A, Ref& extra_B, Ref& promise) const; + bool cell_unpack(Ref cell_ref, Record_chan_msg_close& data) const; + bool cell_unpack_chan_msg_close(Ref cell_ref, Ref& extra_A, Ref& extra_B, Ref& promise) const; + bool pack(vm::CellBuilder& cb, const Record_chan_msg_close& data) const; + bool pack_chan_msg_close(vm::CellBuilder& cb, Ref extra_A, Ref extra_B, Ref promise) const; + bool cell_pack(Ref& cell_ref, const Record_chan_msg_close& data) const; + bool cell_pack_chan_msg_close(Ref& cell_ref, Ref extra_A, Ref extra_B, Ref promise) const; + bool unpack(vm::CellSlice& cs, Record_chan_msg_timeout& data) const; + bool unpack_chan_msg_timeout(vm::CellSlice& cs) const; + bool cell_unpack(Ref cell_ref, Record_chan_msg_timeout& data) const; + bool cell_unpack_chan_msg_timeout(Ref cell_ref) const; + bool pack(vm::CellBuilder& cb, const Record_chan_msg_timeout& data) const; + bool pack_chan_msg_timeout(vm::CellBuilder& cb) const; + bool cell_pack(Ref& cell_ref, const Record_chan_msg_timeout& data) const; + bool cell_pack_chan_msg_timeout(Ref& cell_ref) const; + bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; + std::ostream& print_type(std::ostream& os) const override { + return os << "ChanMsg"; + } + int check_tag(const vm::CellSlice& cs) const override; + int get_tag(const vm::CellSlice& cs) const override { + return cs.bselect(2, 11); + } +}; + +struct ChanMsg::Record_chan_msg_init { + typedef ChanMsg type_class; + Ref inc_A; // inc_A : Grams + Ref inc_B; // inc_B : Grams + Ref min_A; // min_A : Grams + Ref min_B; // min_B : Grams + unsigned long long channel_id; // channel_id : uint64 + Record_chan_msg_init() = default; + Record_chan_msg_init(Ref _inc_A, Ref _inc_B, Ref _min_A, Ref _min_B, unsigned long long _channel_id) : inc_A(std::move(_inc_A)), inc_B(std::move(_inc_B)), min_A(std::move(_min_A)), min_B(std::move(_min_B)), channel_id(_channel_id) {} +}; + +struct ChanMsg::Record_chan_msg_close { + typedef ChanMsg type_class; + Ref extra_A; // extra_A : Grams + Ref extra_B; // extra_B : Grams + Ref promise; // promise : ChanSignedPromise + Record_chan_msg_close() = default; + Record_chan_msg_close(Ref _extra_A, Ref _extra_B, Ref _promise) : extra_A(std::move(_extra_A)), extra_B(std::move(_extra_B)), promise(std::move(_promise)) {} +}; + +extern const ChanMsg t_ChanMsg; + +// +// headers for type `ChanSignedMsg` +// + +struct ChanSignedMsg final : TLB_Complex { + enum { chan_signed_msg }; + static constexpr int cons_len_exact = 0; + struct Record; + bool skip(vm::CellSlice& cs) const override; + bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; + bool unpack(vm::CellSlice& cs, Record& data) const; + bool unpack_chan_signed_msg(vm::CellSlice& cs, Ref& sig_A, Ref& sig_B, Ref& msg) const; + bool cell_unpack(Ref cell_ref, Record& data) const; + bool cell_unpack_chan_signed_msg(Ref cell_ref, Ref& sig_A, Ref& sig_B, Ref& msg) const; + bool pack(vm::CellBuilder& cb, const Record& data) const; + bool pack_chan_signed_msg(vm::CellBuilder& cb, Ref sig_A, Ref sig_B, Ref msg) const; + bool cell_pack(Ref& cell_ref, const Record& data) const; + bool cell_pack_chan_signed_msg(Ref& cell_ref, Ref sig_A, Ref sig_B, Ref msg) const; + bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; + std::ostream& print_type(std::ostream& os) const override { + return os << "ChanSignedMsg"; + } + int check_tag(const vm::CellSlice& cs) const override; + int get_tag(const vm::CellSlice& cs) const override { + return 0; + } +}; + +struct ChanSignedMsg::Record { + typedef ChanSignedMsg type_class; + Ref sig_A; // sig_A : Maybe ^bits512 + Ref sig_B; // sig_B : Maybe ^bits512 + Ref msg; // msg : ChanMsg + Record() = default; + Record(Ref _sig_A, Ref _sig_B, Ref _msg) : sig_A(std::move(_sig_A)), sig_B(std::move(_sig_B)), msg(std::move(_msg)) {} +}; + +extern const ChanSignedMsg t_ChanSignedMsg; + +// +// headers for type `ChanData` +// + +struct ChanData final : TLB_Complex { + enum { chan_data }; + static constexpr int cons_len_exact = 0; + struct Record { + typedef ChanData type_class; + Ref config; // config : ^ChanConfig + Ref state; // state : ^ChanState + Record() = default; + Record(Ref _config, Ref _state) : config(std::move(_config)), state(std::move(_state)) {} + }; + int get_size(const vm::CellSlice& cs) const override { + return 0x20000; + } + bool skip(vm::CellSlice& cs) const override { + return cs.advance_ext(0x20000); + } + bool validate_skip(int* ops, vm::CellSlice& cs, bool weak = false) const override; + bool unpack(vm::CellSlice& cs, Record& data) const; + bool unpack_chan_data(vm::CellSlice& cs, Ref& config, Ref& state) const; + bool cell_unpack(Ref cell_ref, Record& data) const; + bool cell_unpack_chan_data(Ref cell_ref, Ref& config, Ref& state) const; + bool pack(vm::CellBuilder& cb, const Record& data) const; + bool pack_chan_data(vm::CellBuilder& cb, Ref config, Ref state) const; + bool cell_pack(Ref& cell_ref, const Record& data) const; + bool cell_pack_chan_data(Ref& cell_ref, Ref config, Ref state) const; + bool print_skip(PrettyPrinter& pp, vm::CellSlice& cs) const override; + std::ostream& print_type(std::ostream& os) const override { + return os << "ChanData"; + } + int check_tag(const vm::CellSlice& cs) const override; + int get_tag(const vm::CellSlice& cs) const override { + return 0; + } +}; + +extern const ChanData t_ChanData; + // declarations of constant types used // ## 1 @@ -9123,6 +9561,8 @@ extern const HASH_UPDATE t_HASH_UPDATE_Account; extern const RefT t_Ref_HASH_UPDATE_Account; // ^TransactionDescr extern const RefT t_Ref_TransactionDescr; +// uint16 +extern const UInt t_uint16; // HashmapAug 64 ^Transaction CurrencyCollection extern const HashmapAug t_HashmapAug_64_Ref_Transaction_CurrencyCollection; // HashmapAugE 256 AccountBlock CurrencyCollection @@ -9134,9 +9574,7 @@ extern const Maybe t_Maybe_VarUInteger_3; // Maybe int32 extern const Maybe t_Maybe_int32; // ^[$_ gas_used:(VarUInteger 7) gas_limit:(VarUInteger 7) gas_credit:(Maybe (VarUInteger 3)) mode:int8 exit_code:int32 exit_arg:(Maybe int32) vm_steps:uint32 vm_init_state_hash:bits256 vm_final_state_hash:bits256 ] -extern const RefT t_Ref_TYPE_1625; -// uint16 -extern const UInt t_uint16; +extern const RefT t_Ref_TYPE_1626; // Maybe TrStoragePhase extern const Maybe t_Maybe_TrStoragePhase; // Maybe TrCreditPhase @@ -9168,7 +9606,7 @@ extern const HashmapE t_HashmapE_256_LibDescr; // Maybe BlkMasterInfo extern const Maybe t_Maybe_BlkMasterInfo; // ^[$_ overload_history:uint64 underload_history:uint64 total_balance:CurrencyCollection total_validator_fees:CurrencyCollection libraries:(HashmapE 256 LibDescr) master_ref:(Maybe BlkMasterInfo) ] -extern const RefT t_Ref_TYPE_1639; +extern const RefT t_Ref_TYPE_1640; // ^McStateExtra extern const RefT t_Ref_McStateExtra; // Maybe ^McStateExtra @@ -9206,13 +9644,13 @@ extern const RefT t_Ref_McBlockExtra; // Maybe ^McBlockExtra extern const Maybe t_Maybe_Ref_McBlockExtra; // ^[$_ from_prev_blk:CurrencyCollection to_next_blk:CurrencyCollection imported:CurrencyCollection exported:CurrencyCollection ] -extern const RefT t_Ref_TYPE_1650; -// ^[$_ fees_imported:CurrencyCollection recovered:CurrencyCollection created:CurrencyCollection minted:CurrencyCollection ] extern const RefT t_Ref_TYPE_1651; +// ^[$_ fees_imported:CurrencyCollection recovered:CurrencyCollection created:CurrencyCollection minted:CurrencyCollection ] +extern const RefT t_Ref_TYPE_1652; // ## 3 extern const NatWidth t_natwidth_3; // ^[$_ fees_collected:CurrencyCollection funds_created:CurrencyCollection ] -extern const RefT t_Ref_TYPE_1655; +extern const RefT t_Ref_TYPE_1656; // BinTree ShardDescr extern const BinTree t_BinTree_ShardDescr; // ^(BinTree ShardDescr) @@ -9236,7 +9674,7 @@ extern const NatWidth t_natwidth_16; // Maybe ExtBlkRef extern const Maybe t_Maybe_ExtBlkRef; // ^[$_ flags:(## 16) {<= flags 1} validator_info:ValidatorInfo prev_blocks:OldMcBlocksInfo after_key_block:Bool last_key_block:(Maybe ExtBlkRef) block_create_stats:flags.0?BlockCreateStats ] -extern const RefT t_Ref_TYPE_1669; +extern const RefT t_Ref_TYPE_1670; // ^SignedCertificate extern const RefT t_Ref_SignedCertificate; // HashmapE 16 CryptoSignaturePair @@ -9244,7 +9682,7 @@ extern const HashmapE t_HashmapE_16_CryptoSignaturePair; // Maybe ^InMsg extern const Maybe t_Maybe_Ref_InMsg; // ^[$_ prev_blk_signatures:(HashmapE 16 CryptoSignaturePair) recover_create_msg:(Maybe ^InMsg) mint_msg:(Maybe ^InMsg) ] -extern const RefT t_Ref_TYPE_1677; +extern const RefT t_Ref_TYPE_1678; // Hashmap 16 ValidatorDescr extern const Hashmap t_Hashmap_16_ValidatorDescr; // HashmapE 16 ValidatorDescr @@ -9289,6 +9727,16 @@ extern const Maybe t_Maybe_Ref_BlockSignatures; extern const RefT t_Ref_TopBlockDescr; // HashmapE 96 ^TopBlockDescr extern const HashmapE t_HashmapE_96_Ref_TopBlockDescr; +// MERKLE_PROOF Block +extern const MERKLE_PROOF t_MERKLE_PROOF_Block; +// ^(MERKLE_PROOF Block) +extern const RefT t_Ref_MERKLE_PROOF_Block; +// MERKLE_PROOF ShardState +extern const MERKLE_PROOF t_MERKLE_PROOF_ShardState; +// ^(MERKLE_PROOF ShardState) +extern const RefT t_Ref_MERKLE_PROOF_ShardState; +// ^ProducerInfo +extern const RefT t_Ref_ProducerInfo; // ^ComplaintDescr extern const RefT t_Ref_ComplaintDescr; // ^ValidatorComplaint @@ -9306,7 +9754,7 @@ extern const NatWidth t_natwidth_24; // HashmapE 4 VmStackValue extern const HashmapE t_HashmapE_4_VmStackValue; // ^[$_ max_limit:int64 cur_limit:int64 credit:int64 ] -extern const RefT t_Ref_TYPE_1715; +extern const RefT t_Ref_TYPE_1717; // HashmapE 256 ^Cell extern const HashmapE t_HashmapE_256_Ref_Cell; // uint13 @@ -9325,6 +9773,18 @@ extern const RefT t_Ref_VmCont; extern const RefT t_Ref_DNSRecord; // HashmapE 16 ^DNSRecord extern const HashmapE t_HashmapE_16_Ref_DNSRecord; +// ^MsgAddressInt +extern const RefT t_Ref_MsgAddressInt; +// bits512 +extern const Bits t_bits512; +// ^bits512 +extern const RefT t_Ref_bits512; +// Maybe ^bits512 +extern const Maybe t_Maybe_Ref_bits512; +// ^ChanConfig +extern const RefT t_Ref_ChanConfig; +// ^ChanState +extern const RefT t_Ref_ChanState; // declaration of type name registration function extern bool register_simple_types(std::function func); diff --git a/submodules/ton/tonlib-src/crypto/block/block-parse.cpp b/submodules/ton/tonlib-src/crypto/block/block-parse.cpp index 125d2a192b3..c62854d4543 100644 --- a/submodules/ton/tonlib-src/crypto/block/block-parse.cpp +++ b/submodules/ton/tonlib-src/crypto/block/block-parse.cpp @@ -241,6 +241,14 @@ bool MsgAddressInt::extract_std_address(vm::CellSlice& cs, ton::WorkchainId& wor return false; } +bool MsgAddressInt::extract_std_address(Ref cs_ref, block::StdAddress& addr, bool rewrite) const { + return extract_std_address(std::move(cs_ref), addr.workchain, addr.addr, rewrite); +} + +bool MsgAddressInt::extract_std_address(vm::CellSlice& cs, block::StdAddress& addr, bool rewrite) const { + return extract_std_address(cs, addr.workchain, addr.addr, rewrite); +} + bool MsgAddressInt::store_std_address(vm::CellBuilder& cb, ton::WorkchainId workchain, const ton::StdSmcAddress& addr) const { if (workchain >= -128 && workchain < 128) { @@ -263,6 +271,14 @@ Ref MsgAddressInt::pack_std_address(ton::WorkchainId workchain, c } } +bool MsgAddressInt::store_std_address(vm::CellBuilder& cb, const block::StdAddress& addr) const { + return store_std_address(cb, addr.workchain, addr.addr); +} + +Ref MsgAddressInt::pack_std_address(const block::StdAddress& addr) const { + return pack_std_address(addr.workchain, addr.addr); +} + const MsgAddressInt t_MsgAddressInt; bool MsgAddress::validate_skip(int* ops, vm::CellSlice& cs, bool weak) const { diff --git a/submodules/ton/tonlib-src/crypto/block/block-parse.h b/submodules/ton/tonlib-src/crypto/block/block-parse.h index b2ed9c95eec..1c490383d4e 100644 --- a/submodules/ton/tonlib-src/crypto/block/block-parse.h +++ b/submodules/ton/tonlib-src/crypto/block/block-parse.h @@ -298,8 +298,13 @@ struct MsgAddressInt final : TLB_Complex { bool rewrite = true) const; bool extract_std_address(vm::CellSlice& cs, ton::WorkchainId& workchain, ton::StdSmcAddress& addr, bool rewrite = true) const; + bool extract_std_address(Ref cs_ref, block::StdAddress& addr, bool rewrite = true) const; + bool extract_std_address(vm::CellSlice& cs, block::StdAddress& addr, bool rewrite = true) const; bool store_std_address(vm::CellBuilder& cb, ton::WorkchainId workchain, const ton::StdSmcAddress& addr) const; Ref pack_std_address(ton::WorkchainId workchain, const ton::StdSmcAddress& addr) const; + + bool store_std_address(vm::CellBuilder& cb, const block::StdAddress& addr) const; + Ref pack_std_address(const block::StdAddress& addr) const; }; extern const MsgAddressInt t_MsgAddressInt; diff --git a/submodules/ton/tonlib-src/crypto/block/block.cpp b/submodules/ton/tonlib-src/crypto/block/block.cpp index c7b437a6375..9e2caef5e95 100644 --- a/submodules/ton/tonlib-src/crypto/block/block.cpp +++ b/submodules/ton/tonlib-src/crypto/block/block.cpp @@ -27,6 +27,7 @@ #include "td/utils/crypto.h" #include "td/utils/tl_storers.h" #include "td/utils/misc.h" +#include "td/utils/Random.h" namespace block { using namespace std::literals::string_literals; @@ -369,14 +370,14 @@ std::unique_ptr MsgProcessedUptoCollection::unpack(t return v && v->valid ? std::move(v) : std::unique_ptr{}; } -bool MsgProcessedUpto::contains(const MsgProcessedUpto& other) const & { +bool MsgProcessedUpto::contains(const MsgProcessedUpto& other) const& { return ton::shard_is_ancestor(shard, other.shard) && mc_seqno >= other.mc_seqno && (last_inmsg_lt > other.last_inmsg_lt || (last_inmsg_lt == other.last_inmsg_lt && !(last_inmsg_hash < other.last_inmsg_hash))); } bool MsgProcessedUpto::contains(ton::ShardId other_shard, ton::LogicalTime other_lt, td::ConstBitPtr other_hash, - ton::BlockSeqno other_mc_seqno) const & { + ton::BlockSeqno other_mc_seqno) const& { return ton::shard_is_ancestor(shard, other_shard) && mc_seqno >= other_mc_seqno && (last_inmsg_lt > other_lt || (last_inmsg_lt == other_lt && !(last_inmsg_hash < other_hash))); } @@ -1546,6 +1547,89 @@ bool unpack_CreatorStats(Ref cs, DiscountedCounter& mc_cnt, Disco } } +/* + * + * Monte Carlo simulator for computing the share of shardchain blocks generated by each validator + * + */ + +bool MtCarloComputeShare::compute() { + ok = false; + if (W.size() >= (1U << 31) || W.empty()) { + return false; + } + K = std::min(K, N); + if (K <= 0 || iterations <= 0) { + return false; + } + double tot_weight = 0., acc = 0.; + for (int i = 0; i < N; i++) { + if (W[i] <= 0.) { + return false; + } + tot_weight += W[i]; + } + CW.resize(N); + RW.resize(N); + for (int i = 0; i < N; i++) { + CW[i] = acc; + acc += W[i] /= tot_weight; + RW[i] = 0.; + } + R0 = 0.; + H.resize(N); + A.resize(K); + for (long long it = 0; it < iterations; ++it) { + gen_vset(); + } + for (int i = 0; i < N; i++) { + RW[i] = W[i] * (RW[i] + R0) / (double)iterations; + } + return ok = true; +} + +void MtCarloComputeShare::gen_vset() { + double total_wt = 1.; + int hc = 0; + for (int i = 0; i < K; i++) { + CHECK(total_wt > 0); + double inv_wt = 1. / total_wt; + R0 += inv_wt; + for (int j = 0; j < i; j++) { + RW[A[j]] -= inv_wt; + } + // double p = drand48() * total_wt; + double p = (double)td::Random::fast_uint64() * total_wt / (1. * (1LL << 32) * (1LL << 32)); + for (int h = 0; h < hc; h++) { + if (p < H[h].first) { + break; + } + p += H[h].second; + } + int a = -1, b = N, c; + while (b - a > 1) { + c = ((a + b) >> 1); + if (CW[c] <= p) { + a = c; + } else { + b = c; + } + } + CHECK(a >= 0 && a < N); + CHECK(total_wt >= W[a]); + total_wt -= W[a]; + double x = CW[a]; + c = hc++; + while (c > 0 && H[c - 1].first > x) { + H[c] = H[c - 1]; + --c; + } + H[c].first = x; + H[c].second = W[a]; + A[i] = a; + } +} + /* * * Other block-related functions @@ -1723,7 +1807,7 @@ ton::AccountIdPrefixFull interpolate_addr(const ton::AccountIdPrefixFull& src, c unsigned long long mask = (std::numeric_limits::max() >> (d - 32)); return ton::AccountIdPrefixFull{dest.workchain, (dest.account_id_prefix & ~mask) | (src.account_id_prefix & mask)}; } else { - int mask = (-1 >> d); + int mask = (int)(~0U >> d); return ton::AccountIdPrefixFull{(dest.workchain & ~mask) | (src.workchain & mask), src.account_id_prefix}; } } diff --git a/submodules/ton/tonlib-src/crypto/block/block.h b/submodules/ton/tonlib-src/crypto/block/block.h index 5184a349938..6c460e3182b 100644 --- a/submodules/ton/tonlib-src/crypto/block/block.h +++ b/submodules/ton/tonlib-src/crypto/block/block.h @@ -163,12 +163,12 @@ struct MsgProcessedUpto { MsgProcessedUpto(ton::ShardId _shard, ton::BlockSeqno _mcseqno, ton::LogicalTime _lt, td::ConstBitPtr _hash) : shard(_shard), mc_seqno(_mcseqno), last_inmsg_lt(_lt), last_inmsg_hash(_hash) { } - bool operator<(const MsgProcessedUpto& other) const & { + bool operator<(const MsgProcessedUpto& other) const& { return shard < other.shard || (shard == other.shard && mc_seqno < other.mc_seqno); } - bool contains(const MsgProcessedUpto& other) const &; + bool contains(const MsgProcessedUpto& other) const&; bool contains(ton::ShardId other_shard, ton::LogicalTime other_lt, td::ConstBitPtr other_hash, - ton::BlockSeqno other_mc_seqno) const &; + ton::BlockSeqno other_mc_seqno) const&; // NB: this is for checking whether we have already imported an internal message bool already_processed(const EnqueuedMsgDescr& msg) const; bool can_check_processed() const { @@ -596,6 +596,62 @@ struct BlockProofChain { td::Status validate(td::CancellationToken cancellation_token = {}); }; +// compute the share of shardchain blocks generated by each validator using Monte Carlo method +class MtCarloComputeShare { + int K, N; + long long iterations; + std::vector W; + std::vector CW, RW; + std::vector> H; + std::vector A; + double R0; + bool ok; + + public: + MtCarloComputeShare(int subset_size, const std::vector& weights, long long iteration_count = 1000000) + : K(subset_size), N((int)weights.size()), iterations(iteration_count), W(weights), ok(false) { + compute(); + } + MtCarloComputeShare(int subset_size, int set_size, const double* weights, long long iteration_count = 1000000) + : K(subset_size), N(set_size), iterations(iteration_count), W(weights, weights + set_size), ok(false) { + compute(); + } + bool is_ok() const { + return ok; + } + const double* share_array() const { + return ok ? RW.data() : nullptr; + } + const double* weights_array() const { + return ok ? W.data() : nullptr; + } + double operator[](int i) const { + return ok ? RW.at(i) : -1.; + } + double share(int i) const { + return ok ? RW.at(i) : -1.; + } + double weight(int i) const { + return ok ? W.at(i) : -1.; + } + int size() const { + return N; + } + int subset_size() const { + return K; + } + long long performed_iterations() const { + return iterations; + } + + private: + bool set_error() { + return ok = false; + } + bool compute(); + void gen_vset(); +}; + int filter_out_msg_queue(vm::AugmentedDictionary& out_queue, ton::ShardIdFull old_shard, ton::ShardIdFull subshard); std::ostream& operator<<(std::ostream& os, const ShardId& shard_id); diff --git a/submodules/ton/tonlib-src/crypto/block/block.tlb b/submodules/ton/tonlib-src/crypto/block/block.tlb index 1744a071b29..b2a80132aef 100644 --- a/submodules/ton/tonlib-src/crypto/block/block.tlb +++ b/submodules/ton/tonlib-src/crypto/block/block.tlb @@ -272,6 +272,7 @@ transaction$0111 account_addr:bits256 lt:uint64 old:^X new:^X = MERKLE_UPDATE X; update_hashes#72 {X:Type} old_hash:bits256 new_hash:bits256 = HASH_UPDATE X; +!merkle_proof#03 {X:Type} virtual_hash:bits256 depth:uint16 virtual_root:^X = MERKLE_PROOF X; acc_trans#5 account_addr:bits256 transactions:(HashmapAug 64 ^Transaction CurrencyCollection) @@ -731,7 +732,10 @@ top_block_descr_set#4ac789f3 collection:(HashmapE 96 ^TopBlockDescr) = TopBlockD // // VALIDATOR MISBEHAVIOR COMPLAINTS // -no_blk_gen mc_blk_ref:ExtBlkRef from_utime:uint32 to_utime:uint32 state_proof:^Cell prod_proof:^Cell = ComplaintDescr; +prod_info#34 utime:uint32 mc_blk_ref:ExtBlkRef state_proof:^(MERKLE_PROOF Block) + prod_proof:^(MERKLE_PROOF ShardState) = ProducerInfo; +no_blk_gen from_utime:uint32 prod_info:^ProducerInfo = ComplaintDescr; +no_blk_gen_diff prod_info_old:^ProducerInfo prod_info_new:^ProducerInfo = ComplaintDescr; validator_complaint#bc validator_pubkey:uint256 description:^ComplaintDescr created_at:uint32 severity:uint8 reward_addr:uint256 paid:Grams suggested_fine:Grams suggested_fine_part:uint32 = ValidatorComplaint; complaint_status#2d complaint:^ValidatorComplaint voters:(HashmapE 16 True) vset_id:uint256 weight_remaining:int64 = ValidatorComplaintStatus; @@ -808,3 +812,25 @@ cap_method_pubkey#71f4 = SmcCapability; cap_is_wallet#2177 = SmcCapability; cap_name#ff name:Text = SmcCapability; +// +// PAYMENT CHANNELS +// + +chan_config$_ init_timeout:uint32 close_timeout:uint32 a_key:bits256 b_key:bits256 + a_addr:^MsgAddressInt b_addr:^MsgAddressInt channel_id:uint64 = ChanConfig; + +chan_state_init$000 signed_A:Bool signed_B:Bool min_A:Grams min_B:Grams expire_at:uint32 A:Grams B:Grams = ChanState; +chan_state_close$001 signed_A:Bool signed_B:Bool promise_A:Grams promise_B:Grams expire_at:uint32 A:Grams B:Grams = ChanState; +chan_state_payout$010 A:Grams B:Grams = ChanState; + +chan_promise$_ channel_id:uint64 promise_A:Grams promise_B:Grams = ChanPromise; +chan_signed_promise#_ sig:(Maybe ^bits512) promise:ChanPromise = ChanSignedPromise; + +chan_msg_init#27317822 inc_A:Grams inc_B:Grams min_A:Grams min_B:Grams channel_id:uint64 = ChanMsg; +chan_msg_close#f28ae183 extra_A:Grams extra_B:Grams promise:ChanSignedPromise = ChanMsg; +chan_msg_timeout#43278a28 = ChanMsg; + +chan_signed_msg$_ sig_A:(Maybe ^bits512) sig_B:(Maybe ^bits512) msg:ChanMsg = ChanSignedMsg; + +chan_data$_ config:^ChanConfig state:^ChanState = ChanData; + diff --git a/submodules/ton/tonlib-src/crypto/block/check-proof.cpp b/submodules/ton/tonlib-src/crypto/block/check-proof.cpp index 6d991256a6c..6720ad407c4 100644 --- a/submodules/ton/tonlib-src/crypto/block/check-proof.cpp +++ b/submodules/ton/tonlib-src/crypto/block/check-proof.cpp @@ -31,7 +31,7 @@ namespace block { using namespace std::literals::string_literals; -td::Status check_block_header_proof(td::Ref root, ton::BlockIdExt blkid, ton::Bits256* store_shard_hash_to, +td::Status check_block_header_proof(td::Ref root, ton::BlockIdExt blkid, ton::Bits256* store_state_hash_to, bool check_state_hash, td::uint32* save_utime, ton::LogicalTime* save_lt) { ton::RootHash vhash{root->get_hash().bits()}; if (vhash != blkid.root_hash) { @@ -53,7 +53,7 @@ td::Status check_block_header_proof(td::Ref root, ton::BlockIdExt blki if (save_lt) { *save_lt = info.end_lt; } - if (store_shard_hash_to) { + if (store_state_hash_to) { vm::CellSlice upd_cs{vm::NoVmSpec(), blk.state_update}; if (!(upd_cs.is_special() && upd_cs.prefetch_long(8) == 4 // merkle update && upd_cs.size_ext() == 0x20228)) { @@ -61,11 +61,11 @@ td::Status check_block_header_proof(td::Ref root, ton::BlockIdExt blki } auto upd_hash = upd_cs.prefetch_ref(1)->get_hash(0); if (!check_state_hash) { - *store_shard_hash_to = upd_hash.bits(); - } else if (store_shard_hash_to->compare(upd_hash.bits())) { + *store_state_hash_to = upd_hash.bits(); + } else if (store_state_hash_to->compare(upd_hash.bits())) { return td::Status::Error(PSTRING() << "state hash mismatch in block header of " << blkid.to_str() << " : header declares " << upd_hash.bits().to_hex(256) << " expected " - << store_shard_hash_to->to_hex()); + << store_state_hash_to->to_hex()); } } return td::Status::OK(); diff --git a/submodules/ton/tonlib-src/crypto/block/check-proof.h b/submodules/ton/tonlib-src/crypto/block/check-proof.h index cfd3a0d2c18..527f31381a6 100644 --- a/submodules/ton/tonlib-src/crypto/block/check-proof.h +++ b/submodules/ton/tonlib-src/crypto/block/check-proof.h @@ -25,7 +25,7 @@ namespace block { using td::Ref; td::Status check_block_header_proof(td::Ref root, ton::BlockIdExt blkid, - ton::Bits256* store_shard_hash_to = nullptr, bool check_state_hash = false, + ton::Bits256* store_state_hash_to = nullptr, bool check_state_hash = false, td::uint32* save_utime = nullptr, ton::LogicalTime* save_lt = nullptr); td::Status check_shard_proof(ton::BlockIdExt blk, ton::BlockIdExt shard_blk, td::Slice shard_proof); td::Status check_account_proof(td::Slice proof, ton::BlockIdExt shard_blk, const block::StdAddress& addr, diff --git a/submodules/ton/tonlib-src/crypto/block/mc-config.cpp b/submodules/ton/tonlib-src/crypto/block/mc-config.cpp index e192ad8198b..360286b0611 100644 --- a/submodules/ton/tonlib-src/crypto/block/mc-config.cpp +++ b/submodules/ton/tonlib-src/crypto/block/mc-config.cpp @@ -1785,6 +1785,22 @@ std::vector ValidatorSet::export_validator_set() const { return l; } +std::map ValidatorSet::compute_validator_map() const { + std::map res; + for (int i = 0; i < (int)list.size(); i++) { + res.emplace(list[i].pubkey.as_bits256(), i); + } + return res; +} + +std::vector ValidatorSet::export_scaled_validator_weights() const { + std::vector res; + for (const auto& node : list) { + res.push_back((double)node.weight / (double)total_weight); + } + return res; +} + std::vector Config::do_compute_validator_set(const block::CatchainValidatorsConfig& ccv_conf, ton::ShardIdFull shard, const block::ValidatorSet& vset, ton::UnixTime time, diff --git a/submodules/ton/tonlib-src/crypto/block/mc-config.h b/submodules/ton/tonlib-src/crypto/block/mc-config.h index f51b42622cb..dfaf4f6c440 100644 --- a/submodules/ton/tonlib-src/crypto/block/mc-config.h +++ b/submodules/ton/tonlib-src/crypto/block/mc-config.h @@ -71,6 +71,8 @@ struct ValidatorSet { } const ValidatorDescr& at_weight(td::uint64 weight_pos) const; std::vector export_validator_set() const; + std::map compute_validator_map() const; + std::vector export_scaled_validator_weights() const; }; #pragma pack(push, 1) diff --git a/submodules/ton/tonlib-src/crypto/block/test-block.cpp b/submodules/ton/tonlib-src/crypto/block/test-block.cpp deleted file mode 100644 index 6e10ebe9ac5..00000000000 --- a/submodules/ton/tonlib-src/crypto/block/test-block.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* - This file is part of TON Blockchain source code. - - TON Blockchain is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - TON Blockchain is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with TON Blockchain. If not, see . - - In addition, as a special exception, the copyright holders give permission - to link the code of portions of this program with the OpenSSL library. - You must obey the GNU General Public License in all respects for all - of the code used other than OpenSSL. If you modify file(s) with this - exception, you may extend this exception to your version of the file(s), - but you are not obligated to do so. If you do not wish to do so, delete this - exception statement from your version. If you delete this exception statement - from all source files in the program, then also delete it here. - - Copyright 2017-2019 Telegram Systems LLP -*/ -#include "block/block.h" -#include "vm/boc.h" -#include -#include "block-db.h" -#include "block-auto.h" -#include "block-parse.h" -#include "vm/cp0.h" -#include - -using td::Ref; - -int verbosity; - -struct IntError { - std::string err_msg; - IntError(std::string _msg) : err_msg(_msg) { - } - IntError(const char* _msg) : err_msg(_msg) { - } -}; - -td::Ref load_boc(std::string filename) { - std::cerr << "loading bag-of-cell file " << filename << std::endl; - auto bytes_res = block::load_binary_file(filename); - if (bytes_res.is_error()) { - throw IntError{PSTRING() << "cannot load file `" << filename << "` : " << bytes_res.move_as_error()}; - } - vm::BagOfCells boc; - auto res = boc.deserialize(bytes_res.move_as_ok()); - if (res.is_error()) { - throw IntError{PSTRING() << "cannot deserialize bag-of-cells " << res.move_as_error()}; - } - if (res.move_as_ok() <= 0 || boc.get_root_cell().is_null()) { - throw IntError{"cannot deserialize bag-of-cells "}; - } - return boc.get_root_cell(); -} - -void test1() { - block::ShardId id{ton::masterchainId}, id2{ton::basechainId, 0x11efULL << 48}; - std::cout << '[' << id << "][" << id2 << ']' << std::endl; - vm::CellBuilder cb; - cb << id << id2; - std::cout << "ShardIdent.pack() = " << block::tlb::t_ShardIdent.pack(cb, {12, 3, 0x3aeULL << 52}) << std::endl; - std::cout << cb << std::endl; - auto cref = cb.finalize(); - td::Ref cs{true, cref}, cs2; - block::ShardId id3{cs.write()}, id4, id5; - cs >> id4 >> id5; - std::cout << '[' << id3 << "][" << id4 << "][" << id5 << ']' << std::endl; - vm::CellSlice csl{std::move(cref)}; - std::cout << "ShardIdent.get_size() = " << block::tlb::t_ShardIdent.get_size(csl) << std::endl; - std::cout << "MsgAddress.get_size() = " << block::tlb::t_MsgAddress.get_size(csl) << std::endl; - std::cout << "Grams.get_size() = " << block::tlb::t_Grams.get_size(csl) << std::endl; - std::cout << "Grams.as_integer() = " << block::tlb::t_Grams.as_integer(csl) << std::endl; - (csl + 8).print_rec(std::cout); - std::cout << "Grams.get_size() = " << block::tlb::t_Grams.get_size(csl + 8) << std::endl; - std::cout << "Grams.as_integer() = " << block::tlb::t_Grams.as_integer(csl + 8) << std::endl; - - vm::CellSlice csl2{csl}; - block::gen::ShardIdent::Record sh_id; - for (int i = 0; i < 3; i++) { - std::cout << csl2 << std::endl; - bool ok = tlb::unpack(csl2, sh_id); - std::cout << "block::gen::ShardIdent.unpack() = " << ok << std::endl; - if (ok) { - std::cout << " (shard_ident shard_pfx_bits:" << sh_id.shard_pfx_bits << " workchain_id:" << sh_id.workchain_id - << " shard_prefix:" << std::hex << sh_id.shard_prefix << std::dec << ")" << std::endl; - } - } - - block::tlb::ShardIdent::Record shard_id; - for (int i = 0; i < 3; i++) { - std::cout << "ShardIdent.validate() = " << block::tlb::t_ShardIdent.validate(csl) << std::endl; - csl.print_rec(std::cerr); - csl.dump(std::cerr, 7); - std::cout << "ShardIdent.unpack() = " << block::tlb::t_ShardIdent.unpack(csl, shard_id) << std::endl; - if (shard_id.is_valid()) { - std::cout << "shard_pfx_bits:" << shard_id.shard_pfx_bits << " workchain_id:" << shard_id.workchain_id - << " shard_prefix:" << shard_id.shard_prefix << std::endl; - } - } - std::cout << "ShardIdent.skip_validate() = " << block::tlb::t_ShardIdent.validate_skip(csl) << std::endl; - std::cout << "ShardIdent.skip_validate() = " << block::tlb::t_ShardIdent.validate_skip(csl) << std::endl; - std::cout << "ShardIdent.skip_validate() = " << block::tlb::t_ShardIdent.validate_skip(csl) << std::endl; - using namespace td::literals; - std::cout << "Grams.store_intval(239) = " << block::tlb::t_Grams.store_integer_value(cb, "239"_i256) << std::endl; - std::cout << "Grams.store_intval(17239) = " << block::tlb::t_Grams.store_integer_value(cb, "17239"_i256) << std::endl; - std::cout << "Grams.store_intval(-17) = " << block::tlb::t_Grams.store_integer_value(cb, "-17"_i256) << std::endl; - std::cout << "Grams.store_intval(0) = " << block::tlb::t_Grams.store_integer_value(cb, "0"_i256) << std::endl; - std::cout << cb << std::endl; - cs = td::Ref{true, cb.finalize()}; - std::cout << "Grams.store_intval(666) = " << block::tlb::t_Grams.store_integer_value(cb, "666"_i256) << std::endl; - std::cout << cb << std::endl; - cs2 = td::Ref{true, cb.finalize()}; - std::cout << "Grams.validate(cs) = " << block::tlb::t_Grams.validate(*cs) << std::endl; - std::cout << "Grams.validate(cs2) = " << block::tlb::t_Grams.validate(*cs2) << std::endl; - // - block::gen::SplitMergeInfo::Record data; - block::gen::Grams::Record data2; - std::cout << "block::gen::Grams.validate(cs) = " << block::gen::t_Grams.validate(*cs) << std::endl; - std::cout << "block::gen::Grams.validate(cs2) = " << block::gen::t_Grams.validate(*cs2) << std::endl; - std::cout << "[cs = " << cs << "]" << std::endl; - bool ok = tlb::csr_unpack_inexact(cs, data); - std::cout << "block::gen::SplitMergeInfo.unpack(cs, data) = " << ok << std::endl; - if (ok) { - std::cout << " cur_shard_pfx_len = " << data.cur_shard_pfx_len << "; acc_split_depth = " << data.acc_split_depth - << "; this_addr = " << data.this_addr << "; sibling_addr = " << data.sibling_addr << std::endl; - } - ok = tlb::csr_unpack_inexact(cs, data2); - std::cout << "block::gen::Grams.unpack(cs, data2) = " << ok << std::endl; - if (ok) { - std::cout << " amount = " << data2.amount << std::endl; - block::gen::VarUInteger::Record data3; - ok = tlb::csr_type_unpack(data2.amount, block::gen::t_VarUInteger_16, data3); - std::cout << " block::gen::VarUInteger16.unpack(amount, data3) = " << ok << std::endl; - if (ok) { - std::cout << " len = " << data3.len << "; value = " << data3.value << std::endl; - vm::CellBuilder cb; - std::cout << " block::gen::VarUInteger16.pack(cb, data3) = " - << tlb::type_pack(cb, block::gen::t_VarUInteger_16, data3) << std::endl; - std::cout << " cb = " << cb.finalize() << std::endl; - } - } - /* - { - vm::CellBuilder cb; - td::BitArray<256> hash; - std::memset(hash.data(), 0x69, 32); - bool ok = tlb::pack( - cb, block::gen::Test::Record{1000000000000, {170239, -888, {239017, "1000000000000000000"_ri256}, hash}, 17}); - std::cout << " block::gen::Test::pack(cb, {1000000000000, ...}) = " << ok << std::endl; - std::cout << " cb = " << cb << std::endl; - auto cell = cb.finalize(); - vm::CellSlice cs{cell}; - cs.print_rec(std::cout); - block::gen::Test::Record data; - std::cout << " block::gen::Test::validate_ref(cell) = " << block::gen::t_Test.validate_ref(cell) << std::endl; - ok = tlb::unpack(cs, data); - std::cout << " block::gen::Test::unpack(cs, data) = " << ok << std::endl; - if (ok) { - std::cout << "a:" << data.a << " b:" << data.r1.b << " c:" << data.r1.c << " d:" << data.r1.r1.d - << " e:" << data.r1.r1.e << " f:" << data.r1.f << " g:" << data.g << std::endl; - } - std::cout << " block::gen::Test::print_ref(cell) = "; - block::gen::t_Test.print_ref(std::cout, cell, 2); - block::gen::t_CurrencyCollection.print_ref(std::cout, cell, 2); - std::cout << std::endl; - } - */ - std::cout << "Grams.add_values() = " << block::tlb::t_Grams.add_values(cb, cs.write(), cs2.write()) << std::endl; - std::cout << cb << std::endl; - std::cout << "block::gen::t_HashmapAug_64_...print_type() = " - << block::gen::t_HashmapAug_64_Ref_Transaction_CurrencyCollection << std::endl; -} - -void test2(vm::CellSlice& cs) { - std::cout << "Bool.validate() = " << block::tlb::t_Bool.validate(cs) << std::endl; - std::cout << "UInt16.validate() = " << block::tlb::t_uint16.validate(cs) << std::endl; - std::cout << "HashmapE(32,UInt16).validate() = " << block::tlb::HashmapE(32, block::tlb::t_uint16).validate(cs) - << std::endl; - std::cout << "block::gen::HashmapE(32,UInt16).validate() = " - << block::gen::HashmapE{32, block::gen::t_uint16}.validate(cs) << std::endl; -} - -void usage() { - std::cout << "usage: test-block []\n\tor test-block -h\n"; - std::exit(2); -} - -int main(int argc, char* const argv[]) { - int i; - int new_verbosity_level = VERBOSITY_NAME(INFO); - auto zerostate = std::make_unique(); - while ((i = getopt(argc, argv, "hv:")) != -1) { - switch (i) { - case 'v': - new_verbosity_level = VERBOSITY_NAME(FATAL) + (verbosity = td::to_integer(td::Slice(optarg))); - break; - case 'h': - usage(); - std::exit(2); - default: - usage(); - std::exit(2); - } - } - SET_VERBOSITY_LEVEL(new_verbosity_level); - try { - bool done = false; - while (optind < argc) { - auto boc = load_boc(argv[optind++]); - if (boc.is_null()) { - std::cerr << "(invalid boc)" << std::endl; - std::exit(2); - } else { - done = true; - vm::CellSlice cs{vm::NoVm(), boc}; - cs.print_rec(std::cout); - std::cout << std::endl; - block::gen::t_Block.print_ref(std::cout, boc); - std::cout << std::endl; - if (!block::gen::t_Block.validate_ref(boc)) { - std::cout << "(invalid Block)" << std::endl; - } else { - std::cout << "(valid Block)" << std::endl; - } - } - } - if (!done) { - test1(); - } - } catch (IntError& err) { - std::cerr << "caught internal error " << err.err_msg << std::endl; - return 1; - } catch (vm::VmError& err) { - std::cerr << "caught vm error " << err.get_msg() << std::endl; - return 1; - } - return 0; -} diff --git a/submodules/ton/tonlib-src/crypto/block/test-weight-distr.cpp b/submodules/ton/tonlib-src/crypto/block/test-weight-distr.cpp new file mode 100644 index 00000000000..a94b791cd3d --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/block/test-weight-distr.cpp @@ -0,0 +1,199 @@ +/* + This file is part of TON Blockchain source code. + + TON Blockchain is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + TON Blockchain is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with TON Blockchain. If not, see . + + In addition, as a special exception, the copyright holders give permission + to link the code of portions of this program with the OpenSSL library. + You must obey the GNU General Public License in all respects for all + of the code used other than OpenSSL. If you modify file(s) with this + exception, you may extend this exception to your version of the file(s), + but you are not obligated to do so. If you do not wish to do so, delete this + exception statement from your version. If you delete this exception statement + from all source files in the program, then also delete it here. + + Copyright 2020 Telegram Systems LLP +*/ +#include +#include "td/utils/Random.h" +#include "td/utils/misc.h" +#include "block/block.h" +#include + +const int MAX_N = 1000, MAX_K = 100, DEFAULT_K = 7; + +int verbosity; +int N, K = DEFAULT_K; +long long iterations = 1000000; + +td::uint64 TWL, WL[MAX_N]; +double W[MAX_N], CW[MAX_N + 1], RW[MAX_N], R0; +int A[MAX_N], C[MAX_N]; +long long TC; + +void gen_vset() { + static std::pair H[MAX_N]; + double total_wt = 1.; + int hc = 0; + for (int i = 0; i < K; i++) { + CHECK(total_wt > 0); + double inv_wt = 1. / total_wt; + R0 += inv_wt; // advanced mtcarlo stats + for (int j = 0; j < i; j++) { + RW[A[j]] -= inv_wt; // advanced mtcarlo stats + } + // double p = drand48() * total_wt; + double p = (double)td::Random::fast_uint64() * total_wt / (1. * (1LL << 32) * (1LL << 32)); + for (int h = 0; h < hc; h++) { + if (p < H[h].first) { + break; + } + p += H[h].second; + } + int a = -1, b = N, c; + while (b - a > 1) { + c = ((a + b) >> 1); + if (CW[c] <= p) { + a = c; + } else { + b = c; + } + } + CHECK(a >= 0 && a < N); + CHECK(total_wt >= W[a]); + total_wt -= W[a]; + double x = CW[a]; + c = hc++; + while (c > 0 && H[c - 1].first > x) { + H[c] = H[c - 1]; + --c; + } + H[c].first = x; + H[c].second = W[a]; + A[i] = a; + C[a]++; // simple mtcarlo stats + // std::cout << a << ' '; + } + // std::cout << std::endl; + ++TC; // simple mtcarlo stats +} + +void mt_carlo() { + for (int i = 0; i < N; i++) { + C[i] = 0; + RW[i] = 0.; + } + TC = 0; + R0 = 0.; + std::cout << "running " << iterations << " steps of Monte Carlo simulation\n"; + for (long long it = 0; it < iterations; ++it) { + gen_vset(); + } + for (int i = 0; i < N; i++) { + RW[i] = W[i] * (RW[i] + R0) / (double)iterations; + } +} + +double B[MAX_N]; + +void compute_bad_approx() { + static double S[MAX_K + 1]; + S[0] = 1.; + for (int i = 1; i <= K; i++) { + S[i] = 0.; + } + for (int i = 0; i < N; i++) { + double p = W[i]; + for (int j = K; j > 0; j--) { + S[j] += p * S[j - 1]; + } + } + double Sk = S[K]; + for (int i = 0; i < N; i++) { + double t = 1., p = W[i]; + for (int j = 1; j <= K; j++) { + t = S[j] - p * t; + } + B[i] = 1. - t / Sk; + } +} + +void usage() { + std::cout + << "usage: test-weight-distr [-k][-m][-s]\nReads the set of validator " + "weights from stdin and emulates validator shard distribution load\n\t-k \tSets the number of " + "validators generating each shard\n\t-m \tMonte Carlo simulation steps\n"; + std::exit(2); +} + +int main(int argc, char* const argv[]) { + int i; + int new_verbosity_level = VERBOSITY_NAME(INFO); + // long seed = 0; + while ((i = getopt(argc, argv, "hs:k:m:v:")) != -1) { + switch (i) { + case 'k': + K = td::to_integer(td::Slice(optarg)); + CHECK(K > 0 && K <= 100); + break; + case 'm': + iterations = td::to_integer(td::Slice(optarg)); + CHECK(iterations > 0); + break; + case 's': + // seed = td::to_integer(td::Slice(optarg)); + // srand48(seed); + break; + case 'v': + new_verbosity_level = VERBOSITY_NAME(FATAL) + (verbosity = td::to_integer(td::Slice(optarg))); + break; + case 'h': + usage(); + std::exit(2); + default: + usage(); + std::exit(2); + } + } + SET_VERBOSITY_LEVEL(new_verbosity_level); + for (N = 0; N < MAX_N && (std::cin >> WL[N]); N++) { + CHECK(WL[N] > 0); + TWL += WL[N]; + } + CHECK(std::cin.eof()); + CHECK(N > 0 && TWL > 0 && N <= MAX_N); + K = std::min(K, N); + CHECK(K > 0 && K <= MAX_K); + double acc = 0.; + for (i = 0; i < N; i++) { + CW[i] = acc; + acc += W[i] = (double)WL[i] / (double)TWL; + std::cout << "#" << i << ":\t" << W[i] << std::endl; + } + compute_bad_approx(); + mt_carlo(); + std::cout << "result of Monte Carlo simulation (" << iterations << " iterations):" << std::endl; + std::cout << "idx\tweight\tmtcarlo1\tmtcarlo2\tapprox\n"; + for (i = 0; i < N; i++) { + std::cout << "#" << i << ":\t" << W[i] << '\t' << (double)C[i] / (double)iterations << '\t' << RW[i] << '\t' << B[i] + << std::endl; + } + // same computation, but using a MtCarloComputeShare object + block::MtCarloComputeShare MT(K, N, W, iterations); + std::cout << "-----------------------\n"; + for (i = 0; i < N; i++) { + std::cout << '#' << i << ":\t" << MT.weight(i) << '\t' << MT.share(i) << std::endl; + } + return 0; +} diff --git a/submodules/ton/tonlib-src/crypto/block/transaction.cpp b/submodules/ton/tonlib-src/crypto/block/transaction.cpp index 0e3ad5f267d..3f5a1ae6fb1 100644 --- a/submodules/ton/tonlib-src/crypto/block/transaction.cpp +++ b/submodules/ton/tonlib-src/crypto/block/transaction.cpp @@ -1429,6 +1429,9 @@ int Transaction::try_action_send_msg(const vm::CellSlice& cs0, ActionPhase& ap, if (!tlb::csr_unpack(msg.info, erec)) { return -1; } + if (act_rec.mode & ~3) { + return -1; // invalid mode for an external message + } info.src = std::move(erec.src); info.dest = std::move(erec.dest); // created_lt and created_at are ignored diff --git a/submodules/ton/tonlib-src/crypto/block/transaction.h b/submodules/ton/tonlib-src/crypto/block/transaction.h index e7191e07cbc..c1cfbc545e1 100644 --- a/submodules/ton/tonlib-src/crypto/block/transaction.h +++ b/submodules/ton/tonlib-src/crypto/block/transaction.h @@ -151,8 +151,6 @@ struct ActionPhaseConfig { struct CreditPhase { td::RefInt256 due_fees_collected; block::CurrencyCollection credit; - // td::RefInt256 credit; - // Ref credit_extra; }; struct ComputePhase { @@ -233,8 +231,6 @@ struct Account { ton::UnixTime last_paid; vm::CellStorageStat storage_stat; block::CurrencyCollection balance; - // td::RefInt256 balance; - // Ref extra_balance; td::RefInt256 due_payment; Ref orig_total_state; // ^Account Ref total_state; // ^Account @@ -325,8 +321,6 @@ struct Transaction { Ref root; Ref new_total_state; Ref new_inner_state; - // Ref extra_balance; - // Ref msg_extra; Ref new_code, new_data, new_library; Ref in_msg, in_msg_state; Ref in_msg_body; diff --git a/submodules/ton/tonlib-src/crypto/common/promiseop.hpp b/submodules/ton/tonlib-src/crypto/common/promiseop.hpp new file mode 100644 index 00000000000..1e14bc7d785 --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/common/promiseop.hpp @@ -0,0 +1,72 @@ +/* + This file is part of TON Blockchain Library. + + TON Blockchain Library is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + TON Blockchain Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with TON Blockchain Library. If not, see . + + Copyright 2020 Telegram Systems LLP +*/ +#pragma once +#include "refcnt.hpp" +#include "td/actor/PromiseFuture.h" + +namespace td { + +template +class BinaryPromiseMerger : public CntObject { + Result first_; + Result second_; + Promise> promise_; + std::atomic pending_; + + public: + BinaryPromiseMerger(Promise> promise) : promise_(std::move(promise)), pending_(2) { + } + static std::pair, Promise> split(Promise> promise) { + auto ref = make_ref(std::move(promise)); + auto& obj = ref.write(); + return std::make_pair(obj.left(), obj.right()); + } + + private: + Promise left() { + return [this, self = Ref(this)](Result res) { + first_ = std::move(res); + work(); + }; + } + Promise right() { + return [this, self = Ref(this)](Result res) { + second_ = std::move(res); + work(); + }; + } + void work() { + if (!--pending_) { + if (first_.is_error()) { + promise_.set_error(first_.move_as_error()); + } else if (second_.is_error()) { + promise_.set_error(second_.move_as_error()); + } else { + promise_.set_result(std::pair(first_.move_as_ok(), second_.move_as_ok())); + } + } + } +}; + +template +std::pair, Promise> split_promise(Promise> promise) { + return BinaryPromiseMerger::split(std::move(promise)); +} + +} // namespace td diff --git a/submodules/ton/tonlib-src/crypto/fift/lib/TonUtil.fif b/submodules/ton/tonlib-src/crypto/fift/lib/TonUtil.fif index bcdb4a7e604..2ebe583cf76 100644 --- a/submodules/ton/tonlib-src/crypto/fift/lib/TonUtil.fif +++ b/submodules/ton/tonlib-src/crypto/fift/lib/TonUtil.fif @@ -36,6 +36,7 @@ library TonUtil // TON Blockchain Fift Library // ( x -- ) Displays a 64-digit hex number { 64 0x. } : 64x. +{ 64 0X. } : 64X. // ( wc addr -- ) Show address in : form { swap ._ .":" 64x. } : .addr // ( wc addr flags -- ) Show address in base64url form diff --git a/submodules/ton/tonlib-src/crypto/openssl/digest.cpp b/submodules/ton/tonlib-src/crypto/openssl/digest.cpp new file mode 100644 index 00000000000..1baf3162b51 --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/openssl/digest.cpp @@ -0,0 +1,63 @@ +#include + +#include "openssl/digest_td.h" + +#include + +namespace digest { +const EVP_MD *OpensslEVP_SHA1::get_evp() { + return EVP_sha1(); +} + +const EVP_MD *OpensslEVP_SHA256::get_evp() { + return EVP_sha256(); +} + +const EVP_MD *OpensslEVP_SHA512::get_evp() { + return EVP_sha512(); +} + +template +void HashCtx::init() { + ctx = EVP_MD_CTX_create(); + reset(); +} + +template +void HashCtx::reset() { + EVP_DigestInit_ex(ctx, H::get_evp(), 0); +} + +template +void HashCtx::clear() { + EVP_MD_CTX_destroy(ctx); + ctx = nullptr; +} + +template +void HashCtx::feed(const void *data, std::size_t len) { + EVP_DigestUpdate(ctx, data, len); +} + +template +std::size_t HashCtx::extract(unsigned char buffer[digest_bytes]) { + unsigned olen = 0; + EVP_DigestFinal_ex(ctx, buffer, &olen); + assert(olen == digest_bytes); + return olen; +} + +template +std::size_t HashCtx::extract(td::MutableSlice slice) { + return extract(slice.ubegin()); +} + +template +std::string HashCtx::extract() { + unsigned char buffer[digest_bytes]; + unsigned olen = 0; + EVP_DigestFinal_ex(ctx, buffer, &olen); + assert(olen == digest_bytes); + return std::string((char *)buffer, olen); +} +} // namespace digest diff --git a/submodules/ton/tonlib-src/crypto/smartcont/CreateState.fif b/submodules/ton/tonlib-src/crypto/smartcont/CreateState.fif index 7866a840f61..c87ce2fb654 100644 --- a/submodules/ton/tonlib-src/crypto/smartcont/CreateState.fif +++ b/submodules/ton/tonlib-src/crypto/smartcont/CreateState.fif @@ -230,21 +230,24 @@ variable special-dict } : create-wallet1 // D x t -- D' -{ idict! not abort"cannot add value" +{ idict! not abort"cannot add value" } : rdict-entry +{ 86400 * } : days* // balance -- dict { dictnew - over -32768 rdict-entry - over 3/4 */ 92 rdict-entry - over 1/2 */ 183 rdict-entry - swap 1/4 */ 366 rdict-entry - 0 548 rdict-entry + over 31 -1<< rdict-entry + over 3/4 */ 91 days* rdict-entry + over 1/2 */ 183 days* rdict-entry + swap 1/4 */ 365 days* rdict-entry + 0 548 days* rdict-entry } : make-rdict +variable wallet2-start-at wallet2-start-at 0! +now 86400 / 1+ 86400 * wallet2-start-at ! // pubkey amount -- { over ."Key " pubkey>$ type ." -> " RWCode2 // code - // data + // data empty_cell // libs 3 roll // balance 0 // split_depth diff --git a/submodules/ton/tonlib-src/crypto/smartcont/auto/elector-code.cpp b/submodules/ton/tonlib-src/crypto/smartcont/auto/elector-code.cpp index 80a983eba96..38e3451ef94 100644 --- a/submodules/ton/tonlib-src/crypto/smartcont/auto/elector-code.cpp +++ b/submodules/ton/tonlib-src/crypto/smartcont/auto/elector-code.cpp @@ -1 +1 @@ -with_tvm_code("elector-code", "te6ccgECXgEADqQAART/APSkE/S88sgLAQIBIAIDAgFIBAUAUaX//xh2omh6AnoCETdKrPgVeSBOKjgQ+BL5ICz4FHkgcXgTeSB4FJhAAgLFBgcCASBHSAIByQgJASqqgjGCEE5Db2SCEM5Db2RZcIBA2zwpAgEgCgsCAUgqKwIBIAwNBOOnAX0iANJJr4G/8BDrskGDX0mvgb7wbZ4IGq+CgWmPqYnAEHoHN9DJr4M/cJBrhY/8EdCQYIDJr4O+cBFtnjYRGfwR7Z4FwYX8oZlBhNAsVADTASgF1A1QKAPUKARQEEGO0CgGXMmvhb3wKgoBqhzbk8BaUhMUBH/YDoaYGAuNhJL4HwfSAYEOOAR0IYgO2ecADpj5DgAEdCLYDtnnBpn5FBCCc5uiXdR0KZCBHtnnARQQgjsroSXUDg4PEAAduwAf8GehpD+kP6Q/rhQ/BFTbPAf6RAGksSHAALGOiAWgEDVVEts84FMCgCD0Dm+hlDAFoAHjDRA1QUNaQhESBMQj+kTtRND0BCFuBKQUsY6HEDVfBXDbPOAE0//TH9Mf0//UAdCDCNcZAdGCEGVMUHTIyx9SQMsfUjDLH1Jgy/9SIMv/ydBRFfkRjocQaF8Icds84SGDD7mOhxBoXwh22zzgBxkZGRcEeo6ENBPbPOAighBOQ29kuo8YNFRSRNs8loIQzkNvZJKEH+JAM3CAQNs84CKCEO52T0u6I4IQ7nZPb7pSELEcHSkeAiDbPAygVQUL2zxUIFOAIPRDUzoBBNs8QgA8gA34MyBuljCDI3GDCJ/Q0wcBwBryifoA+gD6ANHiBKTbPMkC2zxRs4MH9A5voZRfDoD64YEBQNch+gAwUgiptB8ZoFIHvJRfDID54FFbu5RfC4D44G1wUwdVINs8BvkARgmDB/RTlF8KgPfhRlAQNxAnFVMnFgA0gLzIygcYy/8WzBTLHxLLB8v/AfoCAfoCyx8DIts8AoAg9EPbPDMQRRA0WNs8OlpCBFbbPDENghA7msoAoSCqCyO5jocQvV8Ncts84FEioFF1vY6HEKxfDHPbPOAMXRkZGATAjocQm18LcNs84FNrgwf0Dm+hIJ8w+gBZoAHTPzHT/zBSgL2RMeKOhxCbXwt02zzgUwG5jocQm18Ldds84CDyrPgA+CPIWPoCyx8Uyx8Wy/8Yy/9AOIMH9EMQRUEwFnBwGRkZGgEYghDub0VMWXCAQNs8KQIm2zzI9ABYzxbJ7VQgjoNw2zzgW0YbASCCEPN0SExZghA7msoActs8KQLWMSH6RAGkjo4wghD////+QBNwgEDbPODtRND0BPQEUDODB/Rmb6GOj18EghD////+QBNwgEDbPOE2BfoA0QHI9AAV9AABzxbJ7VSCEPlvcyRwgBjIywVQBM8WUAT6AhLLahLLH8s/yYBA+wApKQBucPgzIG6TXwRw4NDXC/8j+kQBpAK9sZNfA3Dg+AAB1CH7BCDHAJJfBJwB0O0e7VMB8QaC8gDifwSWjoYzNEMA2zzgMCKCEFJnQ3C6jqZUQxXwHoBAIaMiwv+XW3T7AnCDBpEy4gGCEPJnY1CgA0REcAHbPOA0IYIQVnRDcLrjAjMggx6wHykgIQKgMgL6RHD4M9DXC//tRND0BASkWr2xIW6xkl8E4Ns8bFFSFb0EsxSxkl8D4PgAAZFbjp30BPQE+gBDNNs8cMjKABP0APQAWaD6AgHPFsntVOJdQQOiA4MI1xgg0x/TD9Mf0//RA4IQVnRDULrypSHbPDDTB4AgsxKwwFPyqdMfAYIQjoEnirryqdP/0z8wRWb5EfKiVQLbPIIQ1nRSQKBAM3CAQNs8IiMpARyOiYQfQDNwgEDbPOFfAykBGNs8MlmAEPQOb6EwASYEUNs8U5OAIPQOb6E7CpNfCn7hCds8NFtsIkk3GNs8MiHBAZMYXwjgIG5aUyQlA75TI4MH9A5voZRfBG1/4ds8MAH5AALbPFMVvZlfA20Cc6nUAAKSNDTiU1CAEPQOb6ExlF8HbXDg+CPIyx9AZoAQ9ENUIAShUTOyJFAzBNs8QDSDB/RDAcL/kzFtceABciZRJwIqkjA0jolDUNs8MRWgUETiRRNERts8KEIALIAi+DMg0NMHAcAS8qiAYNch0z/0BNEAHIAtyMsHFMwS9ADL/8o/AprQ2zw0NDRTRYMH9A5voZNfBnDh0//TP/oA0gDRUhaptB8WoFJQtghRVaECyMv/yz8B+gISygBARYMH9EMjqwICqgIStghRM6FEQ9s8WVJFAERwgBjIywVQB88WWPoCFctqE8sfyz8hwv+Syx+RMeLJAfsAAgEgLC0CAUg8PQADacICASAuLwIBIDAxA6dNs8gCL4M/kAUwG6k18HcOAiji9TJIAg9A5voY4g0x8xINMf0/8wUAS68rn4I1ADoMjLH1jPFkAEgCD0QwKTE18D4pJsIeJ/iuYgbpIwcN4B2zx/haO0ID9yAEPgz0NMP0w8x0w/RcbYJcG1/jkEpgwf0fG+lII4yAvoA0x/TH9P/0//RA6MEyMt/FMofUkDL/8nQURq2CMjLHxPL/8v/QBSBAaD0QQOkQxORMuIBs+YwNFi2CFMBuZdfB21wbVMR4G2K5jM0pVySbxHkcCCK5jY2WyKAyMzQD9QB2zw0+CMluZNfCHDgcPgzbpRfCPAi4IAR+DPQ+gD6APoA0x/RU2G5lF8M8CLgBJRfC/Ai4AaTXwpw4CMQSVEyUHfwJCDAACCzKwYQWxBKEDlN3ds8I44QMWxSyPQA9AABzxbJ7VTwIuHwDTL4IwGgpsQptgmAEPgz0IF1GOABkA4EBoPSSb6UgjiEB039RGbYIAdMfMdcL/wPTH9P/MdcL/0EwFG8EUAVvAgSSbCHisxQBSAJvIgFvEASkU0i+jpBUZQbbPFMCvJRsIiICkTDikTTiUza+EzUBXsAAUkO5ErGXXwRtcG1TEeBTAaWSbxHkbxBvEHBTAG1tiuY0NDQ2UlW68rFQREMTNgA0cAKOEwJvIiFvEAJvESSoqw8StggSoFjkMDEB/gZvIgFvJFMdgwf0Dm+h8r36ADHTPzHXC/9TnLmOXVE6qKsPUkC2CFFEoSSqOy6pBFGVoFGJoIIQjoEniiOSgHOSgFPiyMsHyx9SQMv/UqDLPyOUE8v/ApEz4lQiqIAQ9ENwJMjL/xrLP1AF+gIYygBAGoMH9EMIEEUTFJJsMeI3ASIhjoVMANs8CpFb4gSkJG4VF0UCuoAQ1yHXCw9ScLYIUxOggBLIywdSMMsfyx8Yyw8Xyw8ayz8T9ADJcPgz0NcL/1MY2zwJ9ARQU6AooAn5ABBJEDhAZXBt2zxANYAg9EMDyPQAEvQAEvQAAc8Wye1Ufzk6AEaCEE5WU1RwggDE/8jLEBXL/4Md+gIUy2oTyx8Syz/MyXH7AAAoBsjLHxXLHxPL//QAAfoCAfoC9AAAliOAIPR8b6UgjjwC0z/T/1MVuo4uNAP0BPoA+gAoqwJRmaFQKaAEyMs/Fsv/EvQAAfoCAfoCWM8WVCAFgCD0QwNwAZJfA+KRMuIBswIBID4/Ad1DGAJPgzbpJbcOFx+DPQ1wv/+Cj6RAGkAr2xkltw4IAi+DMgbpNfA3Dg8A0wMgLQgCjXIdcLH/gjUROhXLmTXwZw4FyhwTyRMZEw4oAR+DPQ+gAwA6BSAqFwbRA0ECNwcNs8yPQA9AABzxbJ7VR/hGA5MAds8bFGTXwNw4QL0BFExgCD0Dm+hk18EcOGAQNch1wv/gCL4MyHbPIAk+DNY2zyxjhNwyMoAEvQA9AABzxbJ7VTwJjB/4F8DcIF1AQAN5Ns8f48yJIAg9HxvpSCPIwLTHzD4I7tTFL2wjxUxVBVE2zwUoFR2E1RzWNs8A1BUcAHekTLiAbPmbGFus4FpBQgAYIW6SW3CVAfkAAbriA0QBgCD0Zm+hkjBw4ds8MGwzIMIAjoQQNNs8joUwECPbPOISU0NEACgFyPQAFPQAEvQAAfoCyx/L/8ntVAGYcFMAf463JoMH9HxvpSCOqALT/9M/MfoA0gDRlDFRM6COkVR3CKmEUWagUhegS7DbPAkD4lBToASRMuIBs+YwNQO6UyG7sPK7EqABoUUBcnAgf46tJIMH9HxvpSCOngLT/9M/MfoA0gDRlDFRM6COh1QYiNs8BwPiUEOgA5Ey4gGz5jAzAbryu0UAMlMSgwf0Dm+hlPoAMKCRMOLIAfoCAoMH9EMAKgbIyx8Vyx9QA/oCAfoC9ADKAMoAyQIBIElKAgEgWFkCASBLTAICclRVAlO2SFtnkJ/tsdOqIlBg/o/N9KQR0YBbZ4pCDeBKAG3gQFImXEA2YlzNhDBPUAIBWE1OAiesDoDtnkGD+gc30MdBbZ5JGDbxQE9QAl+vS22eCBqvgsGPtsdPqIlAEHo/N9KQR0cBbZ43g6kIN4EoAbeBAUiZcQDZiXM2EMBaUwIo2zwQNV8FgCD0Dm+hkjBt4ds8bGFaUwJK2zxtgx+OEiSAEPR+b6UyIZVSA28CAt4Bs+YwMwPQ2zxvCANvBFFSAB7TBwHALfKJ1PQE0//SP9EALtIHAcC88onT/9TTH9MH0//6APoA0x/RAB7TH9Mf0//0BPoA+gD0BNECAWpWVwFCqyztRND0BSBukltw4Ns8ECZfBoMH9A5voZP6ADCSMHDiXQAjuH7UTQ9AUgbpIwcJTQ1wsf4oAYe6rtRND0BSBumDBwVHAAbVMR4Ns8bYT/jickgwf0fm+lII4YAvoA0x8x0x/T/9P/0W8EUhBvAlADbwICkTLiAbPmMDOF0BSbmHXbPBA1XwWDH22OFFESgCD0fm+lMiGVUgNvAgLeAbMS5mwhhaAgFYW1wAIO1E0PQE9AT0BPoA0x/T/9EBbbCle1E0PQFIG6SMG3g2zwQJl8GbYT/jhsigwf0fm+lIJ0C+gAwUhBvAlADbwICkTLiAbPmMDGBdADOz4DtRND0BDH0BDCDB/QOb6GT+gAwkjBw4oAAg0NMf0x/6APoA9ATSANIA0Q=="); +with_tvm_code("elector-code", "te6ccgECYAEADt0AART/APSkE/S88sgLAQIBIAIDAgFIBAUAUaX//xh2omh6AnoCETdKrPgVeSBOKjgQ+BL5ICz4FHkgcXgTeSB4FJhAAgLFBgcCASBHSAIByQgJASqqgjGCEE5Db2SCEM5Db2RZcIBA2zwpAgEgCgsCAUgqKwIBIAwNBOOnAX0iANJJr4G/8BDrskGDX0mvgb7wbZ4IGq+CgWmPqYnAEHoHN9DJr4M/cJBrhY/8EdCQYIDJr4O+cBFtnjYRGfwR7Z4FwYX8oZlBhNAsVADTASgF1A1QKAPUKARQEEGO0CgGXMmvhb3wKgoBqhzbk8BcVBMUBH/YDoaYGAuNhJL4HwfSAYEOOAR0IYgO2ecADpj5DgAEdCLYDtnnBpn5FBCCc5uiXdR0KZCBHtnnARQQgjsroSXUDg4PEAAduwAf8GehpD+kP6Q/rhQ/BFTbPAf6RAGksSHAALGOiAWgEDVVEts84FMCgCD0Dm+hlDAFoAHjDRA1QUNcQhESBMQj+kTtRND0BCFuBKQUsY6HEDVfBXDbPOAE0//TH9Mf0//UAdCDCNcZAdGCEGVMUHTIyx9SQMsfUjDLH1Jgy/9SIMv/ydBRFfkRjocQaF8Icds84SGDD7mOhxBoXwh22zzgBxkZGRcEeo6ENBPbPOAighBOQ29kuo8YNFRSRNs8loIQzkNvZJKEH+JAM3CAQNs84CKCEO52T0u6I4IQ7nZPb7pSELEcHSkeAiDbPAygVQUL2zxUIFOAIPRDVToBBNs8QgA8gA34MyBuljCDI3GDCJ/Q0wcBwBryifoA+gD6ANHiBKTbPMkC2zxRs4MH9A5voZRfDoD64YEBQNch+gAwUgiptB8ZoFIHvJRfDID54FFbu5RfC4D44G1wUwdVINs8BvkARgmDB/RTlF8KgPfhRlAQNxAnFVUnFgA0gLzIygcYy/8WzBTLHxLLB8v/AfoCAfoCyx8DIts8AoAg9EPbPDMQRRA0WNs8OlxCBFbbPDENghA7msoAoSCqCyO5jocQvV8Ncts84FEioFF1vY6HEKxfDHPbPOAMXxkZGATAjocQm18LcNs84FNrgwf0Dm+hIJ8w+gBZoAHTPzHT/zBSgL2RMeKOhxCbXwt02zzgUwG5jocQm18Ldds84CDyrPgA+CPIWPoCyx8Uyx8Wy/8Yy/9AOIMH9EMQRUEwFnBwGRkZGgEYghDub0VMWXCAQNs8KQIm2zzI9ABYzxbJ7VQgjoNw2zzgW0YbASCCEPN0SExZghA7msoActs8KQLWMSH6RAGkjo4wghD////+QBNwgEDbPODtRND0BPQEUDODB/Rmb6GOj18EghD////+QBNwgEDbPOE2BfoA0QHI9AAV9AABzxbJ7VSCEPlvcyRwgBjIywVQBM8WUAT6AhLLahLLH8s/yYBA+wApKQBucPgzIG6TXwRw4NDXC/8j+kQBpAK9sZNfA3Dg+AAB1CH7BCDHAJJfBJwB0O0e7VMB8QaC8gDifwSWjoYzNEMA2zzgMCKCEFJnQ3C6jqZUQxXwHoBAIaMiwv+XW3T7AnCDBpEy4gGCEPJnY1CgA0REcAHbPOA0IYIQVnRDcLrjAjMggx6wHykgIQKgMgL6RHD4M9DXC//tRND0BASkWr2xIW6xkl8E4Ns8bFFSFb0EsxSxkl8D4PgAAZFbjp30BPQE+gBDNNs8cMjKABP0APQAWaD6AgHPFsntVOJfQQOiA4MI1xgg0x/TD9Mf0//RA4IQVnRDULrypSHbPDDTB4AgsxKwwFPyqdMfAYIQjoEnirryqdP/0z8wRWb5EfKiVQLbPIIQ1nRSQKBAM3CAQNs8IiMpARyOiYQfQDNwgEDbPOFfAykBGNs8MlmAEPQOb6EwASYEUNs8U5OAIPQOb6E7CpNfCn7hCds8NFtsIkk3GNs8MiHBAZMYXwjgIG5cVSQlA75TI4MH9A5voZRfBG1/4ds8MAH5AALbPFMVvZlfA20Cc6nUAAKSNDTiU1CAEPQOb6ExlF8HbXDg+CPIyx9AZoAQ9ENUIAShUTOyJFAzBNs8QDSDB/RDAcL/kzFtceABciZTJwIqkjA0jolDUNs8MRWgUETiRRNERts8KEIALIAi+DMg0NMHAcAS8qiAYNch0z/0BNEAHIAtyMsHFMwS9ADL/8o/AprQ2zw0NDRTRYMH9A5voZNfBnDh0//TP/oA0gDRUhaptB8WoFJQtghRVaECyMv/yz8B+gISygBARYMH9EMjqwICqgIStghRM6FEQ9s8WVRFAERwgBjIywVQB88WWPoCFctqE8sfyz8hwv+Syx+RMeLJAfsAAgEgLC0CAUg8PQADacICASAuLwIBIDAxA6dNs8gCL4M/kAUwG6k18HcOAiji9TJIAg9A5voY4g0x8xINMf0/8wUAS68rn4I1ADoMjLH1jPFkAEgCD0QwKTE18D4pJsIeJ/iuYgbpIwcN4B2zx/hcO0ID9yAEPgz0NMP0w8x0w/RcbYJcG1/jkEpgwf0fG+lII4yAvoA0x/TH9P/0//RA6MEyMt/FMofUkDL/8nQURq2CMjLHxPL/8v/QBSBAaD0QQOkQxORMuIBs+YwNFi2CFMBuZdfB21wbVMR4G2K5jM0pVySbxHkcCCK5jY2WyKAyMzQD9QB2zw0+CMluZNfCHDgcPgzbpRfCPAi4IAR+DPQ+gD6APoA0x/RU2G5lF8M8CLgBJRfC/Ai4AaTXwpw4CMQSVEyUHfwJCDAACCzKwYQWxBKEDlN3ds8I44QMWxSyPQA9AABzxbJ7VTwIuHwDTL4IwGgpsQptgmAEPgz0IF9GOABkA4EBoPSSb6UgjiEB039RGbYIAdMfMdcL/wPTH9P/MdcL/0EwFG8EUAVvAgSSbCHisxQBSAJvIgFvEASkU0i+jpBUZQbbPFMCvJRsIiICkTDikTTiUza+EzUBXsAAUkO5ErGXXwRtcG1TEeBTAaWSbxHkbxBvEHBTAG1tiuY0NDQ2UlW68rFQREMTNgA0cAKOEwJvIiFvEAJvESSoqw8StggSoFjkMDEB/gZvIgFvJFMdgwf0Dm+h8r36ADHTPzHXC/9TnLmOXVE6qKsPUkC2CFFEoSSqOy6pBFGVoFGJoIIQjoEniiOSgHOSgFPiyMsHyx9SQMv/UqDLPyOUE8v/ApEz4lQiqIAQ9ENwJMjL/xrLP1AF+gIYygBAGoMH9EMIEEUTFJJsMeI3ASIhjoVMANs8CpFb4gSkJG4VF0UCuoAQ1yHXCw9ScLYIUxOggBLIywdSMMsfyx8Yyw8Xyw8ayz8T9ADJcPgz0NcL/1MY2zwJ9ARQU6AooAn5ABBJEDhAZXBt2zxANYAg9EMDyPQAEvQAEvQAAc8Wye1Ufzk6AEaCEE5WU1RwggDE/8jLEBXL/4Md+gIUy2oTyx8Syz/MyXH7AAAoBsjLHxXLHxPL//QAAfoCAfoC9AAAliOAIPR8b6UgjjwC0z/T/1MVuo4uNAP0BPoA+gAoqwJRmaFQKaAEyMs/Fsv/EvQAAfoCAfoCWM8WVCAFgCD0QwNwAZJfA+KRMuIBswIBID4/Ad1DGAJPgzbpJbcOFx+DPQ1wv/+Cj6RAGkAr2xkltw4IAi+DMgbpNfA3Dg8A0wMgLQgCjXIdcLH/gjUROhXLmTXwZw4FyhwTyRMZEw4oAR+DPQ+gAwA6BSAqFwbRA0ECNwcNs8yPQA9AABzxbJ7VR/hGA5MAds8bFGTXwNw4QL0BFExgCD0Dm+hk18EcOGAQNch1wv/gCL4MyHbPIAk+DNY2zyxjhNwyMoAEvQA9AABzxbJ7VTwJjB/4F8DcIF9AQAN5Ns8f48yJIAg9HxvpSCPIwLTHzD4I7tTFL2wjxUxVBVE2zwUoFR2E1RzWNs8A1BUcAHekTLiAbPmbGFus4FxBQgAYIW6SW3CVAfkAAbriA0QBgCD0Zm+hkjBw4ds8MGwzIMIAjoQQNNs8joUwECPbPOISVUNEACgFyPQAFPQAEvQAAfoCyx/L/8ntVAGYcFMAf463JoMH9HxvpSCOqALT/9M/MfoA0gDRlDFRM6COkVR3CKmEUWagUhegS7DbPAkD4lBToASRMuIBs+YwNQO6UyG7sPK7EqABoUUBcnAgf46tJIMH9HxvpSCOngLT/9M/MfoA0gDRlDFRM6COh1QYiNs8BwPiUEOgA5Ey4gGz5jAzAbryu0UAMlMSgwf0Dm+hlPoAMKCRMOLIAfoCAoMH9EMAKgbIyx8Vyx9QA/oCAfoC9ADKAMoAyQIBIElKAgEgWlsCASBLTAICclZXAlO2SFtnkJ/tsdOqIlBg/o/N9KQR0YBbZ4pCDeBKAG3gQFImXEA2YlzNhDBRUgIBIE1OAmGwojbPBA1XwWDH22OoFESgCD0fm+lII6PAts8XwQjQxNvBFADbwICkTLiAbMS5mwhgXFUCASBPUAInrA6A7Z5Bg/oHN9DHQW2eSRg28UBRUgJdr0ttnggar4LBj7bHTyiJQBB6PzfSkEdGgW2eE6qwN4QoAbeBAUiZcQDZiXM2EMBcVQIo2zwQNV8FgCD0Dm+hkjBt4ds8bGFcVQJK2zxtgx+OEiSAEPR+b6UyIZVSA28CAt4Bs+YwMwPQ2zxvCANvBFNUAB7TBwHALfKJ1PQE0//SP9EALtIHAcC88onT/9TTH9MH0//6APoA0x/RAB7TH9Mf0//0BPoA+gD0BNECAWpYWQFCqyztRND0BSBukltw4Ns8ECZfBoMH9A5voZP6ADCSMHDiXwAjuH7UTQ9AUgbpIwcJTQ1wsf4oAYe6rtRND0BSBumDBwVHAAbVMR4Ns8bYT/jickgwf0fm+lII4YAvoA0x8x0x/T/9P/0W8EUhBvAlADbwICkTLiAbPmMDOF8BSbmHXbPBA1XwWDH22OFFESgCD0fm+lMiGVUgNvAgLeAbMS5mwhhcAgFYXV4AIO1E0PQE9AT0BPoA0x/T/9EBbbCle1E0PQFIG6SMG3g2zwQJl8GbYT/jhsigwf0fm+lIJ0C+gAwUhBvAlADbwICkTLiAbPmMDGBfADOz4DtRND0BDH0BDCDB/QOb6GT+gAwkjBw4oAAg0NMf0x/6APoA9ATSANIA0Q=="); diff --git a/submodules/ton/tonlib-src/crypto/smartcont/auto/elector-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/auto/elector-code.fif index 25f7d47e272..2be991fab1d 100644 --- a/submodules/ton/tonlib-src/crypto/smartcont/auto/elector-code.fif +++ b/submodules/ton/tonlib-src/crypto/smartcont/auto/elector-code.fif @@ -52,6 +52,7 @@ PROGRAM{ 130944 DECLMETHOD compute_returned_stake 104565 DECLMETHOD past_election_ids 81558 DECLMETHOD past_elections + 74376 DECLMETHOD past_elections_list DECLPROC complete_unpack_complaint DECLPROC get_past_complaints 77853 DECLMETHOD show_complaint @@ -2263,7 +2264,7 @@ PROGRAM{ }> past_elections PROC:<{ // - load_data INLINECALLDICT // _23 _24 _25 _26 _27 _28 + load_data INLINECALLDICT // _21 _22 _23 _24 _25 _26 s3 s5 XCHG 5 BLKDROP // past_elections 32 PUSHPOW2 // past_elections id @@ -2276,19 +2277,51 @@ PROGRAM{ DUP // past_elections list fs id found found IF:<{ // past_elections list fs id found s0 s2 XCHG // past_elections list found id fs - unpack_past_election INLINECALLDICT // past_elections list found id _32 _33 _34 _35 _36 _37 _38 - 7 TUPLE // past_elections list found id info - s1 s(-1) PUXC // past_elections list found id id info - PAIR // past_elections list found id _20 - s0 s3 XCHG2 // past_elections id found _20 list + unpack_past_election INLINECALLDICT // past_elections list found id _30 _31 _32 _33 _34 _35 _36 + s7 PUSH + 7 -ROLL // past_elections list found id id _30 _31 _32 _33 _34 _35 _36 + 8 TUPLE // past_elections list found id _17 + s0 s3 XCHG2 // past_elections id found _17 list CONS // past_elections id found list s0 s2 XCHG // past_elections list found id }>ELSE<{ s2 POP // past_elections list found id }> SWAP // past_elections list id found - NOT // past_elections list id _22 - s1 s2 XCHG // past_elections id list _22 + NOT // past_elections list id _20 + s1 s2 XCHG // past_elections id list _20 + }> // past_elections id list + 2 1 BLKDROP2 // list + }> + past_elections_list PROC:<{ + // + load_data INLINECALLDICT // _28 _29 _30 _31 _32 _33 + s3 s5 XCHG + 5 BLKDROP // past_elections + 32 PUSHPOW2 // past_elections id + PUSHNULL // past_elections id list + UNTIL:<{ + s1 s2 XCPU + 32 PUSHINT // past_elections list id past_elections _15=32 + DICTUGETPREV + NULLSWAPIFNOT2 // past_elections list fs id found + DUP // past_elections list fs id found found + IF:<{ // past_elections list fs id found + s0 s2 XCHG // past_elections list found id fs + unpack_past_election INLINECALLDICT // past_elections list found id _37 _38 _39 _40 _41 _42 _43 + 4 BLKDROP // past_elections list found id unfreeze_at stake_held vset_hash + s3 PUSH + s3 s1 s3 XCHG3 // past_elections list found id id unfreeze_at vset_hash stake_held + 4 TUPLE // past_elections list found id _25 + s0 s3 XCHG2 // past_elections id found _25 list + CONS // past_elections id found list + s0 s2 XCHG // past_elections list found id + }>ELSE<{ + s2 POP // past_elections list found id + }> + SWAP // past_elections list id found + NOT // past_elections list id _27 + s1 s2 XCHG // past_elections id list _27 }> // past_elections id list 2 1 BLKDROP2 // list }> diff --git a/submodules/ton/tonlib-src/crypto/smartcont/auto/payment-channel-code.cpp b/submodules/ton/tonlib-src/crypto/smartcont/auto/payment-channel-code.cpp new file mode 100644 index 00000000000..783e49aab4d --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/auto/payment-channel-code.cpp @@ -0,0 +1 @@ +with_tvm_code("payment-channel", "te6ccgECHgEAA2oAART/APSkE/S88sgLAQIBIAIDAgLOBAUACvJwAfANAgEgBgcCASAPEAIBIAgJAgEgCgsAB0MfANgAKV0NMf0x/T/9P/1AHQAdQB0AHTP9GAIBIAwOAgEgDQ4AiwC0gBTAZgw1AHQgwjXGd4B0gBTAZgw1AHQgwjXGd4h+QElnIAfVEFo+RAU8vQQJJI0NeIhmoAgQ1b5EBTy9BKTNTMw4gGAANRwyMoCF8oAFcoAUAP6AgH6AssfAfoCAfoCyYAAfNIA0gD6APoA0x/6APoAMIAIBIBESAgFIGBkCASATFAIBIBUWADUccjKAhfKABXKAFAD+gIB+gLLHwH6AgH6AsmAAQSCEDf+eBBwgBDIywVQBs8WUAT6AhTLahLLH8s/yQH7AIABnPgAUFahI6NSELmTMCKj3lMCvJIwId5RM6BQI6FUMSRz8AlUIgRz8AlyyMoCAfoCAfoCyYAH3AjwBSLAAJgy+CNQB6BQBpE34gvTH4IQQyeKKFIguo4WECZfBjQ0NYAjAvgjuRLy9HBRRAbwCuCAJIIQJzF4IhO6EvL0+gD6APoA+gDTPzCAJwFWErry9IAhU0OgARERAbkBERAB8vKAIlPYuVPYubHy9FDSoFB8oFBasYBcAhFMluZIyFJE14lAnsVNpuZM2EFiROeJTKLCOHjhbUVS8USO8ErGWcFFEBvAK4DBsInBUcAAgVRTwCOAzMzdBRAPwBgL3AnwByLAAJgy+CNQB6BQBpE34g3TH4IQQyeKKFIguo4YWzMzNjY2NoAjBPgjuRTy9BYQNRA0WfAK4IAlghDyiuGDE7oS8vSAIlPWuVPWubHy9FFcsVFLsQX6APoA0gABjhM7WzmAJlC6sBny9HAgEIoHUJkI4w0J0z/6AIBobAoc2zwh8ANUOUPwBCnQ0wJwUiC6jhE7VErgVGRAVHhwD1YS8AsJCJI6PeJxHbqeOBBpCBBqEEUQNEE68AyUXwhsIuLbPIBwdAGbUAdCDCNcZIfkBERCRPZ4zgB9Ub0/5EB3y9BtwAuINlRAtOjownDCAIE26+RAY8vRwB+IAevoAMIAnUT+6E/L0+ABQCaBcuZExkTDiUHagU3C5kTeRMOJTULCcMDQ1FhA1EDRAM/AK4GwiNxAmRUAS8AgADO1E0NTU0QAOAcjMzMntVA=="); diff --git a/submodules/ton/tonlib-src/crypto/smartcont/auto/payment-channel-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/auto/payment-channel-code.fif new file mode 100644 index 00000000000..d5395ff512f --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/auto/payment-channel-code.fif @@ -0,0 +1,571 @@ +// automatically generated from `smartcont/stdlib.fc` `smartcont/payment-channel-code.fc` +PROGRAM{ + DECLPROC unpack_data + DECLPROC pack_data + DECLPROC unpack_config + DECLPROC unwrap_signatures + DECLPROC unpack_state_init + DECLPROC pack_state_init + DECLPROC unpack_state_close + DECLPROC pack_state_close + DECLPROC send_payout + DECLPROC do_payout + DECLPROC with_init + DECLPROC with_close + DECLPROC recv_any + DECLPROC recv_internal + DECLPROC recv_external + unpack_data PROCREF:<{ + // + c4 PUSH // _1 + CTOS // cs + LDREF // _4 cs + LDREF // res res cs + ENDS + }> + pack_data PROCREF:<{ + // config state + SWAP + NEWC // state config _2 + STREF // state _3 + STREF // _4 + ENDC // _5 + c4 POP + }> + unpack_config PROC:<{ + // config + CTOS // cs + 32 LDU // _4 cs + 32 LDU // _4 _7 cs + 256 LDU // _4 _7 _10 cs + 256 LDU // _4 _7 _10 _13 cs + LDREF // _4 _7 _10 _13 _16 cs + SWAP // _4 _7 _10 _13 cs _16 + CTOS // _4 _7 _10 _13 cs _18 + SWAP // _4 _7 _10 _13 _18 cs + LDREF // _4 _7 _10 _13 _18 _19 cs + SWAP // _4 _7 _10 _13 _18 cs _19 + CTOS // _4 _7 _10 _13 _18 cs _21 + SWAP // _4 _7 _10 _13 _18 _21 cs + 64 LDU // res res res res res res res cs + ENDS + }> + unwrap_signatures PROC:<{ + // cs a_key b_key + s0 s2 XCHG // b_key a_key cs + 1 LDI // b_key a_key a? cs + s0 s1 PUSH2 // b_key a_key a? cs a_sig a? + IF:<{ // b_key a_key a? cs a_sig + DROP // b_key a_key a? cs + LDREF // b_key a_key a? _8 cs + SWAP // b_key a_key a? cs _8 + CTOS // b_key a_key a? cs _10 + 9 PUSHPOW2 // b_key a_key a? cs _10 _11=512 + PLDSLICEX // b_key a_key a? cs a_sig + }> // b_key a_key a? cs a_sig + SWAP // b_key a_key a? a_sig cs + 1 LDI // b_key a_key a? a_sig b? cs + s0 s1 PUSH2 // b_key a_key a? a_sig b? cs b_sig b? + IF:<{ // b_key a_key a? a_sig b? cs b_sig + DROP // b_key a_key a? a_sig b? cs + LDREF // b_key a_key a? a_sig b? _18 cs + SWAP // b_key a_key a? a_sig b? cs _18 + CTOS // b_key a_key a? a_sig b? cs _20 + 9 PUSHPOW2 // b_key a_key a? a_sig b? cs _20 _21=512 + PLDSLICEX // b_key a_key a? a_sig b? cs b_sig + }> // b_key a_key a? a_sig b? cs b_sig + OVER // b_key a_key a? a_sig b? cs b_sig cs + HASHSU // b_key a_key a? a_sig b? cs b_sig hash + s5 PUSH // b_key a_key a? a_sig b? cs b_sig hash a? + IF:<{ // b_key a_key a? a_sig b? cs b_sig hash + 31 PUSHINT // b_key a_key a? a_sig b? cs b_sig hash _25 + s1 s5 s7 PUXC2 // b_key hash a? _25 b? cs b_sig hash a_sig a_key + CHKSIGNU // b_key hash a? _25 b? cs b_sig _26 + s1 s4 XCHG // b_key hash a? b_sig b? cs _25 _26 + THROWANYIFNOT + s2 s4 XCHG // b_key b_sig a? hash b? cs + }>ELSE<{ + s4 POP + s5 POP // b_key b_sig a? hash b? cs + }> + OVER // b_key b_sig a? hash b? cs b? + IF:<{ // b_key b_sig a? hash b? cs + 32 PUSHINT // b_key b_sig a? hash b? cs _28 + s3 s5 s6 XCHG3 // _28 cs a? b? hash b_sig b_key + CHKSIGNU // _28 cs a? b? _29 + s1 s4 XCHG // b? cs a? _28 _29 + THROWANYIFNOT + s1 s2 XCHG // cs b? a? + }>ELSE<{ + s5 POP + s3 POP + DROP // cs b? a? + }> + SWAP // cs a? b? + }> + unpack_state_init PROC:<{ + // state + 1 LDI // _1 state + 1 LDI // _1 _4 state + LDGRAMS // _1 _4 _7 state + LDGRAMS // _1 _4 _7 _9 state + 32 LDU // _1 _4 _7 _9 _11 state + LDGRAMS // _1 _4 _7 _9 _11 _14 state + LDGRAMS // _1 _4 _7 _9 _11 _14 _31 _30 + DROP // _1 _4 _7 _9 _11 _14 _16 + }> + pack_state_init PROC:<{ + // signed_A? signed_B? min_A min_B expire_at A B + 0 PUSHINT // signed_A? signed_B? min_A min_B expire_at A B _7 + NEWC // signed_A? signed_B? min_A min_B expire_at A B _7 _8 + 3 STI // signed_A? signed_B? min_A min_B expire_at A B _10 + s1 s7 XCHG // B signed_B? min_A min_B expire_at A signed_A? _10 + 1 STI // B signed_B? min_A min_B expire_at A _12 + s1 s5 XCHG // B A min_A min_B expire_at signed_B? _12 + 1 STI // B A min_A min_B expire_at _14 + s0 s3 XCHG2 // B A expire_at min_B _14 min_A + STGRAMS // B A expire_at min_B _15 + SWAP // B A expire_at _15 min_B + STGRAMS // B A expire_at _16 + 32 STU // B A _18 + SWAP // B _18 A + STGRAMS // B _19 + SWAP // _19 B + STGRAMS // _20 + ENDC // _21 + }> + unpack_state_close PROC:<{ + // state + 1 LDI // _1 state + 1 LDI // _1 _4 state + LDGRAMS // _1 _4 _7 state + LDGRAMS // _1 _4 _7 _9 state + 32 LDU // _1 _4 _7 _9 _11 state + LDGRAMS // _1 _4 _7 _9 _11 _14 state + LDGRAMS // _1 _4 _7 _9 _11 _14 _31 _30 + DROP // _1 _4 _7 _9 _11 _14 _16 + }> + pack_state_close PROC:<{ + // signed_A? signed_B? promise_A promise_B expire_at A B + 1 PUSHINT // signed_A? signed_B? promise_A promise_B expire_at A B _7 + NEWC // signed_A? signed_B? promise_A promise_B expire_at A B _7 _8 + 3 STI // signed_A? signed_B? promise_A promise_B expire_at A B _10 + s1 s7 XCHG // B signed_B? promise_A promise_B expire_at A signed_A? _10 + 1 STI // B signed_B? promise_A promise_B expire_at A _12 + s1 s5 XCHG // B A promise_A promise_B expire_at signed_B? _12 + 1 STI // B A promise_A promise_B expire_at _14 + s0 s3 XCHG2 // B A expire_at promise_B _14 promise_A + STGRAMS // B A expire_at promise_B _15 + SWAP // B A expire_at _15 promise_B + STGRAMS // B A expire_at _16 + 32 STU // B A _18 + SWAP // B _18 A + STGRAMS // B _19 + SWAP // _19 B + STGRAMS // _20 + ENDC // _21 + }> + send_payout PROC:<{ + // s_addr amount channel_id flags + 0x37fe7810 PUSHINT // s_addr amount channel_id flags _4 + 0 PUSHINT // s_addr amount channel_id flags _4 _5=0 + 16 PUSHINT // s_addr amount channel_id flags _4 _5=0 _6=16 + NEWC // s_addr amount channel_id flags _4 _5=0 _6=16 _7 + 6 STU // s_addr amount channel_id flags _4 _5=0 _9 + s0 s6 XCHG2 // _5=0 amount channel_id flags _4 _9 s_addr + STSLICER // _5=0 amount channel_id flags _4 _10 + s0 s4 XCHG2 // _5=0 _4 channel_id flags _10 amount + STGRAMS // _5=0 _4 channel_id flags _11 + s1 s4 XCHG // flags _4 channel_id _5=0 _11 + 107 STU // flags _4 channel_id _25 + s1 s2 XCHG // flags channel_id _4 _25 + 32 STU // flags channel_id _27 + 64 STU // flags _29 + ENDC // flags _30 + SWAP // _30 flags + SENDRAWMSG + }> + do_payout PROC:<{ + // promise_A promise_B A B a_addr b_addr channel_id + ACCEPT + s5 s6 XCHG2 // channel_id b_addr A B a_addr promise_B promise_A + SUB // channel_id b_addr A B a_addr diff + s3 PUSH // channel_id b_addr A B a_addr diff A + NEGATE // channel_id b_addr A B a_addr diff _10 + s1 s(-1) PUXC // channel_id b_addr A B a_addr diff diff _10 + LESS // channel_id b_addr A B a_addr diff _11 + IF:<{ // channel_id b_addr A B a_addr diff + DROP // channel_id b_addr A B a_addr + s2 PUSH // channel_id b_addr A B a_addr A + NEGATE // channel_id b_addr A B a_addr diff + }> // channel_id b_addr A B a_addr diff + s0 s2 PUSH2 // channel_id b_addr A B a_addr diff diff B + GREATER // channel_id b_addr A B a_addr diff _13 + IF:<{ // channel_id b_addr A B a_addr diff + DROP // channel_id b_addr A B a_addr + OVER // channel_id b_addr A B a_addr diff + }> // channel_id b_addr A B a_addr diff + s3 s3 XCPU // channel_id b_addr diff B a_addr A diff + ADD // channel_id b_addr diff B a_addr A + s2 s3 XCHG2 // channel_id b_addr A a_addr B diff + SUB // channel_id b_addr A a_addr B + s1 s2 s4 XCPU2 + 3 PUSHINT // channel_id b_addr A B a_addr A channel_id _16=3 + send_payout CALLDICT + s2 s0 s3 XCPUXC + 3 PUSHINT // B A b_addr B channel_id _18=3 + send_payout CALLDICT + 2 PUSHINT // B A _20 + NEWC // B A _20 _21 + 3 STI // B A _23 + SWAP // B _23 A + STGRAMS // B _24 + SWAP // _24 B + STGRAMS // _25 + ENDC // _26 + }> + with_init PROC:<{ + // state msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr init_timeout channel_id + s0 s8 XCHG // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr init_timeout state + unpack_state_init CALLDICT // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr init_timeout signed_A? signed_B? min_A min_B expire_at A B + s2 PUSH // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr init_timeout signed_A? signed_B? min_A min_B expire_at A B expire_at + 0 EQINT // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr init_timeout signed_A? signed_B? min_A min_B expire_at A B _18 + IF:<{ // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr init_timeout signed_A? signed_B? min_A min_B expire_at A B + s2 POP // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr init_timeout signed_A? signed_B? min_A min_B B A + NOW // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr init_timeout signed_A? signed_B? min_A min_B B A _19 + s0 s7 XCHG2 // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr A signed_A? signed_B? min_A min_B B _19 init_timeout + ADD // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr A signed_A? signed_B? min_A min_B B expire_at + s0 s6 XCHG2 // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at A + }>ELSE<{ + s7 POP // channel_id msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at A + }> + s0 s11 XCHG // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at msg + 32 LDU // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at op msg + 0x43278a28 PUSHINT // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at op msg _25 + s2 s(-1) PUXC // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at op msg op _25 + EQUAL // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at op msg _26 + IFJMP:<{ // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at op msg + s2 s6 XCHG + 6 BLKDROP + s4 POP + s4 POP + s5 POP // channel_id b_addr A B expire_at a_addr + 35 PUSHINT // channel_id b_addr A B expire_at a_addr _27 + s0 s2 XCHG + NOW // channel_id b_addr A B _27 a_addr expire_at _28 + LESS // channel_id b_addr A B _27 a_addr _29 + s1 s2 XCHG // channel_id b_addr A B a_addr _27 _29 + THROWANYIFNOT + 0 PUSHINT // channel_id b_addr A B a_addr _31=0 + s4 s4 XCPU + s0 s6 XCHG // _31=0 _32=0 A B a_addr b_addr channel_id + do_payout CALLDICT // _33 + }> // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at op msg + 36 PUSHINT // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at op msg _34 + 0x27317822 PUSHINT // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at op msg _34 _35 + s1 s3 XCHG // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at _34 msg op _35 + EQUAL // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at _34 msg _36 + s1 s2 XCHG // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at msg _34 _36 + THROWANYIFNOT + LDGRAMS // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at _43 msg + LDGRAMS // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at _43 _45 msg + LDGRAMS // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at _43 _45 _47 msg + LDGRAMS // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at _43 _45 _47 _49 msg + 64 LDU // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at _43 _45 _47 _49 _104 _103 + DROP // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A upd_min_B got_channel_id + 39 PUSHINT // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A upd_min_B got_channel_id _54 + SWAP + 18 s() PUSH // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A upd_min_B _54 got_channel_id channel_id + EQUAL // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A upd_min_B _54 _55 + THROWANYIFNOT + 33 PUSHINT // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A upd_min_B _57 + s4 s3 PUSH2 // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A upd_min_B _57 inc_A inc_B + ADD // channel_id msg_value A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A upd_min_B _57 _58 + s1 17 s() XCHG // channel_id _57 A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A upd_min_B msg_value _58 + LESS // channel_id _57 A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A upd_min_B _59 + s1 16 s() XCHG // channel_id upd_min_B A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A _57 _59 + THROWANYIF + 34 PUSHINT // channel_id upd_min_B A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A _61 + s13 s8 PUSH2 // channel_id upd_min_B A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A _61 msg_signed_A? signed_A? + LESS // channel_id upd_min_B A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A _61 _62 + s13 s8 PUSH2 // channel_id upd_min_B A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A _61 _62 msg_signed_B? signed_B? + LESS // channel_id upd_min_B A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A _61 _62 _63 + OR // channel_id upd_min_B A msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at inc_A inc_B upd_min_A _61 _64 + THROWANYIFNOT + s13 s2 XCHG2 // channel_id upd_min_B inc_B msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at upd_min_A A inc_A + ADD // channel_id upd_min_B inc_B msg_signed_A? msg_signed_B? a_addr b_addr B signed_A? signed_B? min_A min_B expire_at upd_min_A A + s7 s12 XCHG2 // channel_id upd_min_B A msg_signed_A? msg_signed_B? a_addr b_addr upd_min_A signed_A? signed_B? min_A min_B expire_at B inc_B + ADD // channel_id upd_min_B A msg_signed_A? msg_signed_B? a_addr b_addr upd_min_A signed_A? signed_B? min_A min_B expire_at B + s5 s10 XCHG2 // channel_id upd_min_B A B msg_signed_B? a_addr b_addr upd_min_A expire_at signed_B? min_A min_B signed_A? msg_signed_A? + OR // channel_id upd_min_B A B msg_signed_B? a_addr b_addr upd_min_A expire_at signed_B? min_A min_B signed_A? + s2 s5 PUSH2 // channel_id upd_min_B A B msg_signed_B? a_addr b_addr upd_min_A expire_at signed_B? min_A min_B signed_A? min_A upd_min_A + LESS // channel_id upd_min_B A B msg_signed_B? a_addr b_addr upd_min_A expire_at signed_B? min_A min_B signed_A? _69 + IF:<{ // channel_id upd_min_B A B msg_signed_B? a_addr b_addr upd_min_A expire_at signed_B? min_A min_B signed_A? + s2 POP // channel_id upd_min_B A B msg_signed_B? a_addr b_addr min_A expire_at signed_B? signed_A? min_B + s1 s4 XCHG // channel_id upd_min_B A B msg_signed_B? a_addr b_addr signed_A? expire_at signed_B? min_A min_B + }>ELSE<{ + s5 POP // channel_id upd_min_B A B msg_signed_B? a_addr b_addr signed_A? expire_at signed_B? min_A min_B + }> + s2 s7 XCHG2 // channel_id upd_min_B A B min_B a_addr b_addr signed_A? expire_at min_A signed_B? msg_signed_B? + OR // channel_id upd_min_B A B min_B a_addr b_addr signed_A? expire_at min_A signed_B? + s6 s9 PUSH2 // channel_id upd_min_B A B min_B a_addr b_addr signed_A? expire_at min_A signed_B? min_B upd_min_B + LESS // channel_id upd_min_B A B min_B a_addr b_addr signed_A? expire_at min_A signed_B? _71 + IF:<{ // channel_id upd_min_B A B min_B a_addr b_addr signed_A? expire_at min_A signed_B? + s6 POP // channel_id min_B A B signed_B? a_addr b_addr signed_A? expire_at min_A + s5 s8 XCHG // channel_id signed_B? A B min_B a_addr b_addr signed_A? expire_at min_A + }>ELSE<{ + s9 POP // channel_id signed_B? A B min_B a_addr b_addr signed_A? expire_at min_A + }> + s2 s8 PUSH2 // channel_id signed_B? A B min_B a_addr b_addr signed_A? expire_at min_A signed_A? signed_B? + AND // channel_id signed_B? A B min_B a_addr b_addr signed_A? expire_at min_A _72 + IFJMP:<{ // channel_id signed_B? A B min_B a_addr b_addr signed_A? expire_at min_A + s8 POP + 2DROP // channel_id min_A A B min_B a_addr b_addr + s5 s4 XCPU // channel_id b_addr A B min_B a_addr min_A A + GREATER // channel_id b_addr A B min_B a_addr _73 + s2 s3 XCPU // channel_id b_addr A B _73 a_addr min_B B + GREATER // channel_id b_addr A B _73 a_addr _74 + s1 s2 XCHG // channel_id b_addr A B a_addr _73 _74 + OR // channel_id b_addr A B a_addr _75 + IFJMP:<{ // channel_id b_addr A B a_addr + 0 PUSHINT // channel_id b_addr A B a_addr _76=0 + s4 s4 XCPU + s0 s6 XCHG // _76=0 _77=0 A B a_addr b_addr channel_id + do_payout CALLDICT // _78 + }> // channel_id b_addr A B a_addr + DROP + 2 2 BLKDROP2 // A B + 0 PUSHINT // A B _79=0 + s0 s0 s0 PUSH3 // A B _79=0 _80=0 _81=0 _82=0 + DUP // A B _79=0 _80=0 _81=0 _82=0 _83=0 + 2 5 BLKSWAP // _79=0 _80=0 _81=0 _82=0 _83=0 A B + pack_state_close CALLDICT // _84 + }> // channel_id signed_B? A B min_B a_addr b_addr signed_A? expire_at min_A + s3 POP + s3 POP + s7 POP // signed_A? signed_B? A B min_B expire_at min_A + s1 s4 s4 XCHG3 + s0 s3 XCHG // signed_A? signed_B? min_A min_B expire_at A B + pack_state_init CALLDICT // _85 + }> + with_close PROC:<{ + // cs msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr expire_timeout channel_id + s0 s9 XCHG // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr expire_timeout cs + unpack_state_close CALLDICT // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr expire_timeout signed_A? signed_B? promise_A promise_B expire_at A B + s2 PUSH // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr expire_timeout signed_A? signed_B? promise_A promise_B expire_at A B expire_at + 0 EQINT // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr expire_timeout signed_A? signed_B? promise_A promise_B expire_at A B _19 + IF:<{ // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr expire_timeout signed_A? signed_B? promise_A promise_B expire_at A B + s2 POP // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr expire_timeout signed_A? signed_B? promise_A promise_B B A + NOW // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr expire_timeout signed_A? signed_B? promise_A promise_B B A _20 + s0 s7 XCHG2 // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr A signed_A? signed_B? promise_A promise_B B _20 expire_timeout + ADD // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr A signed_A? signed_B? promise_A promise_B B expire_at + s0 s6 XCHG2 // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at A + }>ELSE<{ + s7 POP // channel_id msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at A + }> + s0 s13 XCHG // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at msg + 32 LDU // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at op msg + 0x43278a28 PUSHINT // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at op msg _26 + s2 s(-1) PUXC // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at op msg op _26 + EQUAL // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at op msg _27 + IFJMP:<{ // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at op msg + 2DROP + s3 POP + s3 POP + s6 POP + s6 POP + s6 POP + s6 POP // channel_id A B promise_B expire_at promise_A a_addr b_addr + 35 PUSHINT // channel_id A B promise_B expire_at promise_A a_addr b_addr _28 + s0 s4 XCHG + NOW // channel_id A B promise_B _28 promise_A a_addr b_addr expire_at _29 + LESS // channel_id A B promise_B _28 promise_A a_addr b_addr _30 + s1 s4 XCHG // channel_id A B promise_B b_addr promise_A a_addr _28 _30 + THROWANYIFNOT + s1 s6 XCHG + s3 s5 XCHG + s3 s4 XCHG + -ROT // promise_A promise_B A B a_addr b_addr channel_id + do_payout CALLDICT // _32 + }> // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at op msg + 37 PUSHINT // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at op msg _33 + 0xf28ae183 PUSHINT // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at op msg _33 _34 + s1 s3 XCHG // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at _33 msg op _34 + EQUAL // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at _33 msg _35 + s1 s2 XCHG // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at msg _33 _35 + THROWANYIFNOT + 34 PUSHINT // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at msg _37 + s13 s6 PUSH2 // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at msg _37 msg_signed_A? signed_A? + LESS // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at msg _37 _38 + s13 s6 PUSH2 // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at msg _37 _38 msg_signed_B? signed_B? + LESS // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at msg _37 _38 _39 + OR // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_A? signed_B? promise_A promise_B expire_at msg _37 _40 + THROWANYIFNOT + s5 s12 XCPU // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B msg signed_B? promise_A promise_B expire_at signed_A? msg_signed_A? + OR // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B msg signed_B? promise_A promise_B expire_at signed_A? + s4 s11 XCPU // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B msg signed_A? promise_A promise_B expire_at signed_B? msg_signed_B? + OR // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B msg signed_A? promise_A promise_B expire_at signed_B? + s0 s5 XCHG // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at msg + LDGRAMS // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at _46 msg + LDGRAMS // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg + 1 LDI // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B has_sig msg + SWAP // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg has_sig + IF:<{ // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg + LDREF // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B _55 msg + SWAP // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg _55 + CTOS // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg _57 + 9 PUSHPOW2 // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg _57 _58=512 + PLDSLICEX // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg sig + OVER // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg sig msg + HASHSU // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg sig hash + s0 16 s() XCHG // channel_id A hash msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg sig msg_signed_A? + IFNOT:<{ // channel_id A hash msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg sig + s3 POP // channel_id A hash msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at sig extra_B msg + 31 PUSHINT // channel_id A hash msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at sig extra_B msg _62 + s15 s3 s13 PU2XC // channel_id A hash msg_signed_B? _62 b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at sig extra_B msg hash sig a_key + CHKSIGNU // channel_id A hash msg_signed_B? _62 b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at sig extra_B msg _63 + s1 s13 XCHG // channel_id A hash msg_signed_B? msg b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at sig extra_B _62 _63 + THROWANYIFNOT + s1 s11 XCHG + 0 PUSHINT + s0 s2 XCHG // channel_id A hash msg_signed_B? sig b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A=0 extra_B msg + }>ELSE<{ + s13 POP // channel_id A hash msg_signed_B? sig b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg + }> + s0 s13 XCHG // channel_id A hash msg sig b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg_signed_B? + IFNOT:<{ // channel_id A hash msg sig b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B + DROP // channel_id A hash msg sig b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A + 32 PUSHINT // channel_id A hash msg sig b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A _66 + s13 s11 s10 XCHG3 // channel_id A expire_at msg extra_A _66 a_addr b_addr B signed_B? signed_A? promise_A promise_B hash sig b_key + CHKSIGNU // channel_id A expire_at msg extra_A _66 a_addr b_addr B signed_B? signed_A? promise_A promise_B _67 + s1 s8 XCHG // channel_id A expire_at msg extra_A promise_B a_addr b_addr B signed_B? signed_A? promise_A _66 _67 + THROWANYIFNOT + 0 PUSHINT // channel_id A expire_at msg extra_A promise_B a_addr b_addr B signed_B? signed_A? promise_A extra_B=0 + s0 s7 XCHG // channel_id A expire_at msg extra_A extra_B=0 a_addr b_addr B signed_B? signed_A? promise_A promise_B + }>ELSE<{ + s2 s13 XCHG + s10 POP + s10 POP + DROP // channel_id A expire_at msg extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A promise_B + }> + }>ELSE<{ // channel_id A msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr B signed_B? signed_A? promise_A promise_B expire_at extra_A extra_B msg + s11 POP + 2DROP + s9 POP // channel_id A msg_signed_A? msg_signed_B? expire_at msg a_addr b_addr B signed_B? signed_A? promise_A promise_B + 38 PUSHINT // channel_id A msg_signed_A? msg_signed_B? expire_at msg a_addr b_addr B signed_B? signed_A? promise_A promise_B _70 + s11 s10 XCHG2 // channel_id A promise_B _70 expire_at msg a_addr b_addr B signed_B? signed_A? promise_A msg_signed_A? msg_signed_B? + AND // channel_id A promise_B _70 expire_at msg a_addr b_addr B signed_B? signed_A? promise_A _71 + s1 s9 XCHG // channel_id A promise_B promise_A expire_at msg a_addr b_addr B signed_B? signed_A? _70 _71 + THROWANYIFNOT + 0 PUSHINT // channel_id A promise_B promise_A expire_at msg a_addr b_addr B signed_B? signed_A? extra_A=0 + DUP // channel_id A promise_B promise_A expire_at msg a_addr b_addr B signed_B? signed_A? extra_A=0 extra_B=0 + s8 s10 XCHG + s0 s7 XCHG + s9 s9 XCHG2 + s0 s8 XCHG // channel_id A expire_at msg extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A promise_B + }> + s0 s9 XCHG // channel_id A expire_at promise_B extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A msg + 64 LDU // channel_id A expire_at promise_B extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A _78 msg + LDGRAMS // channel_id A expire_at promise_B extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A _78 _81 msg + LDGRAMS // channel_id A expire_at promise_B extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A _78 _81 _118 _117 + DROP // channel_id A expire_at promise_B extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A got_channel_id update_promise_A update_promise_B + 39 PUSHINT // channel_id A expire_at promise_B extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A got_channel_id update_promise_A update_promise_B _85 + s3 s15 XCPU // channel_id A expire_at promise_B extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A _85 update_promise_A update_promise_B got_channel_id channel_id + EQUAL // channel_id A expire_at promise_B extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A _85 update_promise_A update_promise_B _86 + s1 s3 XCHG // channel_id A expire_at promise_B extra_A extra_B a_addr b_addr B signed_B? signed_A? promise_A update_promise_B update_promise_A _85 _86 + THROWANYIFNOT + ACCEPT + s0 s9 XCHG2 // channel_id A expire_at promise_B update_promise_B extra_B a_addr b_addr B signed_B? signed_A? promise_A update_promise_A extra_A + ADD // channel_id A expire_at promise_B update_promise_B extra_B a_addr b_addr B signed_B? signed_A? promise_A update_promise_A + 2DUP // channel_id A expire_at promise_B update_promise_B extra_B a_addr b_addr B signed_B? signed_A? promise_A update_promise_A promise_A update_promise_A + LESS // channel_id A expire_at promise_B update_promise_B extra_B a_addr b_addr B signed_B? signed_A? promise_A update_promise_A _90 + IF:<{ // channel_id A expire_at promise_B update_promise_B extra_B a_addr b_addr B signed_B? signed_A? promise_A update_promise_A + NIP // channel_id A expire_at promise_B update_promise_B extra_B a_addr b_addr B signed_B? signed_A? promise_A + }>ELSE<{ + DROP // channel_id A expire_at promise_B update_promise_B extra_B a_addr b_addr B signed_B? signed_A? promise_A + }> + s7 s6 XCHG2 // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? update_promise_B extra_B + ADD // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? update_promise_B + s7 s0 PUSH2 // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? update_promise_B promise_B update_promise_B + LESS // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? update_promise_B _92 + IF:<{ // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? update_promise_B + s7 POP // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? + }>ELSE<{ + DROP // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? + }> + s5 s0 PUSH2 // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? signed_A? signed_B? + AND // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? _93 + IFJMP:<{ // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? + DROP + s4 POP + s5 POP // channel_id A b_addr promise_B B promise_A a_addr + s1 s6 XCHG + s3 s5 XCHG + s3 s4 XCHG + s0 s3 s3 XCHG3 // promise_A promise_B A B a_addr b_addr channel_id + do_payout CALLDICT // _94 + }> // channel_id A expire_at promise_B signed_A? promise_A a_addr b_addr B signed_B? + 2 2 BLKDROP2 + s7 POP // signed_B? A expire_at promise_B signed_A? promise_A B + s2 s6 XCHG + s5 s4 s0 XCHG3 + s1 s2 XCHG // signed_A? signed_B? promise_A promise_B expire_at A B + pack_state_close CALLDICT // _95 + }> + recv_any PROC:<{ + // msg_value msg + unpack_data INLINECALLDICT // msg_value msg config state + OVER // msg_value msg config state config + unpack_config CALLDICT // msg_value msg config state init_timeout close_timeout a_key b_key a_addr b_addr channel_id + s9 s4 s3 XCPU2 // msg_value channel_id config state init_timeout close_timeout a_key b_key a_addr b_addr msg a_key b_key + unwrap_signatures CALLDICT // msg_value channel_id config state init_timeout close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? + s9 PUSH // msg_value channel_id config state init_timeout close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? state + CTOS // msg_value channel_id config state init_timeout close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? cs + 3 LDU // msg_value channel_id config state init_timeout close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? state_type cs + 0 PUSHINT // msg_value channel_id config state init_timeout close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? state_type cs _23 + s2 s(-1) PUXC // msg_value channel_id config state init_timeout close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? state_type cs state_type _23 + EQUAL // msg_value channel_id config state init_timeout close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? state_type cs _24 + IF:<{ // msg_value channel_id config state init_timeout close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? state_type cs + s11 POP // msg_value channel_id config cs init_timeout close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? state_type + s10 s13 s(-1) PUXC2 + s4 s3 s(-2) PU2XC + s8 s7 s0 PUSH3 + s0 s15 XCHG + 18 s() PUSH // state_type channel_id config cs msg_signed_B? close_timeout a_key b_key a_addr b_addr msg msg_signed_A? cs msg_value msg msg_signed_A? msg_signed_B? a_addr b_addr init_timeout channel_id + with_init CALLDICT // state_type channel_id config cs msg_signed_B? close_timeout a_key b_key a_addr b_addr msg msg_signed_A? state + s0 s9 XCHG + s0 s8 XCHG // state_type channel_id config state cs close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? + }>ELSE<{ + s10 POP + s13 POP // state_type channel_id config state cs close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? + }> + 1 PUSHINT // state_type channel_id config state cs close_timeout a_key b_key a_addr b_addr msg msg_signed_A? msg_signed_B? _26 + s1 s13 XCHG // msg_signed_B? channel_id config state cs close_timeout a_key b_key a_addr b_addr msg msg_signed_A? state_type _26 + EQUAL // msg_signed_B? channel_id config state cs close_timeout a_key b_key a_addr b_addr msg msg_signed_A? _27 + IF:<{ // msg_signed_B? channel_id config state cs close_timeout a_key b_key a_addr b_addr msg msg_signed_A? + s8 POP // msg_signed_B? channel_id config msg_signed_A? cs close_timeout a_key b_key a_addr b_addr msg + s6 s9 XCHG + s0 s8 XCHG + s6 s10 XCHG + s4 s5 XCHG + s3 s4 XCHG + s1 s3 s10 XCHG3 // config cs msg msg_signed_A? msg_signed_B? a_key b_key a_addr b_addr close_timeout channel_id + with_close CALLDICT // config state + }>ELSE<{ + 8 BLKDROP + 2 2 BLKDROP2 // config state + }> + pack_data INLINECALLDICT + }> + recv_internal PROC:<{ + // msg_value in_msg_cell in_msg + NIP // msg_value in_msg + recv_any CALLDICT + }> + recv_external PROC:<{ + // in_msg + 0 PUSHINT // in_msg _1=0 + SWAP // _1=0 in_msg + recv_any CALLDICT + }> +}END>c diff --git a/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet2-code.cpp b/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet2-code.cpp index f77aba8d4b4..83fb4002dd4 100644 --- a/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet2-code.cpp +++ b/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet2-code.cpp @@ -1 +1 @@ -with_tvm_code("restricted-wallet2", "te6ccgECCwEAAQgAART/APSkE/S88sgLAQIBIAIDAgFIBAUB+PKDCNcYINMf0x8B+CO78mPtRNDTH9P/9ATRU0K68qEEjhIyMzP4AAGkyMsfEsv/9ADJ7VThBPkBVBBU+RDyovgAgPP4MyBukjB/nvgjAdDXCx+hggFRgKkE4iKAEPR7b6UxlvoAMHL7ApEw4pMg10qW0wfUAvsA6NECpMgKAATQMAIBIAYHAgEgCAkAe7y2B2omhAgJBrkPoCaMB5/BmQN0kYP898EYDoa4WP0MEAqMBUgnF8E7eIAUAIej230pjL/QAYULhbBMiYcUABe7Oc7UTQ0x8x1wv/gAEbjJftRNDXCx+AASyx/L//QAye1U"); +with_tvm_code("restricted-wallet2", "te6ccgECDgEAARoAART/APSkE/S88sgLAQIBIAIDAgFIBAUB8vKDCNcYINMf0x8B+CO78mPtRNDTH9P/0x/0BNFTU7ryoQWOFTM0NPgAA6TIyx8Sy/8Syx/0AMntVOEF+QFUEGb5EPKi+AAj+CPbPCOAIPR7b6UxlvoAMHL7ApEw4gGTINdKltMH1AL7AOjRpMjLHxPL/8sf9ADJ7VQNAATQMAIBIAYHAgEgCAkCAUgKCwAXuznO1E0NMfMdcL/4ABG4yX7UTQ1wsfgBDbbYHwR7Z5AMAQm1B1tnkAwBTu1E0IEBINch0x/0BNEC2zz4J28QAoAg9HtvpTGX+gAwoXC2CZEw4g0AOiGOETGA8/gzIG6SMHCU0NcLH+IB3yGSAaGSW3/i"); diff --git a/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet2-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet2-code.fif index afa1724a795..0b69a9c34ec 100644 --- a/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet2-code.fif +++ b/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet2-code.fif @@ -1,32 +1,42 @@ // automatically generated from `smartcont/stdlib.fc` `smartcont/restricted-wallet2-code.fc` PROGRAM{ DECLPROC recv_internal - DECLPROC days_passed + DECLPROC seconds_passed DECLPROC recv_external 85143 DECLMETHOD seqno 78748 DECLMETHOD get_public_key + DECLPROC compute_balance_at + 108602 DECLMETHOD balance_at 104128 DECLMETHOD balance recv_internal PROC:<{ // in_msg DROP // }> - days_passed PROC:<{ - // - -13 PUSHINT // _1=-13 - CONFIGOPTPARAM // p - DUP // p p - ISNULL // p _3 - IF:<{ // p - DROP // - -1 PUSHINT // _4=-1 - }>ELSE<{ // p - NOW // p _6 - SWAP // _6 p - CTOS // _6 _7 - 32 PLDU // _6 _9 - SUB // _10 - 86400 PUSHINT // _10 _11=86400 - DIV // _4 + seconds_passed PROCREF:<{ + // start_at utime + OVER // start_at utime start_at + IFNOT:<{ // start_at utime + NIP // utime + -13 PUSHINT // utime _3=-13 + CONFIGOPTPARAM // utime p + DUP // utime p p + ISNULL // utime p _5 + IF:<{ // utime p + DROP // utime + 0 PUSHINT // utime _6=0 + }>ELSE<{ // utime p + CTOS // utime _8 + 32 PLDU // utime _6 + }> // utime start_at + SWAP // start_at utime + }> // start_at utime + OVER // start_at utime start_at + IF:<{ // start_at utime + SWAP // utime start_at + SUB // _11 + }>ELSE<{ // start_at utime + 2DROP // + -1 PUSHINT // _11=-1 }> }> recv_external PROC:<{ @@ -42,66 +52,73 @@ PROGRAM{ 35 THROWIF c4 PUSH // signature in_msg msg_seqno cs _19 CTOS // signature in_msg msg_seqno cs ds - 32 LDU // signature in_msg msg_seqno cs _24 ds - 256 LDU // signature in_msg msg_seqno cs _24 _27 ds - LDDICT // signature in_msg msg_seqno cs stored_seqno public_key rdict ds + 32 LDU // signature in_msg msg_seqno cs _25 ds + 256 LDU // signature in_msg msg_seqno cs _25 _28 ds + 32 LDU // signature in_msg msg_seqno cs _25 _28 _31 ds + LDDICT // signature in_msg msg_seqno cs stored_seqno public_key start_at rdict ds ENDS - s4 s2 PUSH2 // signature in_msg msg_seqno cs stored_seqno public_key rdict msg_seqno stored_seqno - EQUAL // signature in_msg msg_seqno cs stored_seqno public_key rdict _34 + s5 s3 PUSH2 // signature in_msg msg_seqno cs stored_seqno public_key start_at rdict msg_seqno stored_seqno + EQUAL // signature in_msg msg_seqno cs stored_seqno public_key start_at rdict _38 33 THROWIFNOT - s0 s4 XCHG // signature in_msg rdict cs stored_seqno public_key msg_seqno - IFNOTJMP:<{ // signature in_msg rdict cs stored_seqno public_key - s2 POP + s0 s5 XCHG // signature in_msg rdict cs stored_seqno public_key start_at msg_seqno + IFNOTJMP:<{ // signature in_msg rdict cs stored_seqno public_key start_at s3 POP - s3 POP // public_key stored_seqno rdict + s4 POP + s4 POP // stored_seqno public_key rdict start_at ACCEPT - SWAP // public_key rdict stored_seqno - INC // public_key rdict _38 - NEWC // public_key rdict _38 _39 - 32 STU // public_key rdict _41 - s1 s2 XCHG // rdict public_key _41 - 256 STU // rdict _43 - STDICT // _44 - ENDC // _45 + s0 s3 XCHG // start_at public_key rdict stored_seqno + INC // start_at public_key rdict _42 + NEWC // start_at public_key rdict _42 _43 + 32 STU // start_at public_key rdict _45 + s1 s2 XCHG // start_at rdict public_key _45 + 256 STU // start_at rdict _47 + s1 s2 XCHG // rdict start_at _47 + 32 STU // rdict _49 + STDICT // _50 + ENDC // _51 c4 POP - }> // signature in_msg rdict cs stored_seqno public_key - s0 s4 XCHG // signature public_key rdict cs stored_seqno in_msg - HASHSU // signature public_key rdict cs stored_seqno _48 - s0 s5 s4 XC2PU // stored_seqno public_key rdict cs _48 signature public_key - CHKSIGNU // stored_seqno public_key rdict cs _49 + }> // signature in_msg rdict cs stored_seqno public_key start_at + s0 s5 XCHG // signature start_at rdict cs stored_seqno public_key in_msg + HASHSU // signature start_at rdict cs stored_seqno public_key _54 + s0 s6 s6 XC2PU // public_key start_at rdict cs stored_seqno _54 signature public_key + CHKSIGNU // public_key start_at rdict cs stored_seqno _55 34 THROWIFNOT ACCEPT - days_passed INLINECALLDICT // stored_seqno public_key rdict cs ts - s2 PUSH - 16 PUSHINT // stored_seqno public_key rdict cs ts rdict _57=16 + s3 PUSH + NOW // public_key start_at rdict cs stored_seqno start_at _59 + seconds_passed INLINECALLDICT // public_key start_at rdict cs stored_seqno ts + s3 PUSH + 32 PUSHINT // public_key start_at rdict cs stored_seqno ts rdict _64=32 DICTIGETPREVEQ - NULLSWAPIFNOT2 // stored_seqno public_key rdict cs _98 _97 _99 - NIP // stored_seqno public_key rdict cs value found - IF:<{ // stored_seqno public_key rdict cs value - LDGRAMS // stored_seqno public_key rdict cs _101 _100 - DROP // stored_seqno public_key rdict cs _59 - 2 PUSHINT // stored_seqno public_key rdict cs _59 _61=2 + NULLSWAPIFNOT2 // public_key start_at rdict cs stored_seqno _109 _108 _110 + NIP // public_key start_at rdict cs stored_seqno value found + IF:<{ // public_key start_at rdict cs stored_seqno value + LDGRAMS // public_key start_at rdict cs stored_seqno _112 _111 + DROP // public_key start_at rdict cs stored_seqno _66 + 2 PUSHINT // public_key start_at rdict cs stored_seqno _66 _68=2 RAWRESERVE }>ELSE<{ - DROP // stored_seqno public_key rdict cs - }> // stored_seqno public_key rdict cs + DROP // public_key start_at rdict cs stored_seqno + }> + SWAP // public_key start_at rdict stored_seqno cs WHILE:<{ - DUP // stored_seqno public_key rdict cs cs - SREFS // stored_seqno public_key rdict cs _65 - }>DO<{ // stored_seqno public_key rdict cs - 8 LDU // stored_seqno public_key rdict mode cs - LDREF // stored_seqno public_key rdict mode msg cs - s0 s2 XCHG // stored_seqno public_key rdict cs msg mode + DUP // public_key start_at rdict stored_seqno cs cs + SREFS // public_key start_at rdict stored_seqno cs _72 + }>DO<{ // public_key start_at rdict stored_seqno cs + 8 LDU // public_key start_at rdict stored_seqno mode cs + LDREF // public_key start_at rdict stored_seqno mode msg cs + s0 s2 XCHG // public_key start_at rdict stored_seqno cs msg mode SENDRAWMSG - }> // stored_seqno public_key rdict cs + }> // public_key start_at rdict stored_seqno cs ENDS - s0 s2 XCHG // rdict public_key stored_seqno - INC // rdict public_key _76 - NEWC // rdict public_key _76 _77 - 32 STU // rdict public_key _79 - 256 STU // rdict _81 - STDICT // _82 - ENDC // _83 + INC // public_key start_at rdict _83 + NEWC // public_key start_at rdict _83 _84 + 32 STU // public_key start_at rdict _86 + s1 s3 XCHG // rdict start_at public_key _86 + 256 STU // rdict start_at _88 + 32 STU // rdict _90 + STDICT // _91 + ENDC // _92 c4 POP }> seqno PROC:<{ @@ -118,30 +135,41 @@ PROGRAM{ NIP // cs 256 PLDU // _7 }> - balance PROC:<{ - // - c4 PUSH // _1 - CTOS // _2 - 288 PUSHINT // _2 _5 - SDSKIPFIRST // ds - LDDICT // rdict ds + compute_balance_at PROCREF:<{ + // utime + c4 PUSH // utime _2 + CTOS // utime _3 + 288 PUSHINT // utime _3 _6 + SDSKIPFIRST // utime ds + 32 LDU // utime _10 ds + LDDICT // utime start_at rdict ds ENDS - days_passed INLINECALLDICT // rdict ts - BALANCE // rdict ts _14 + s0 s2 XCHG // rdict start_at utime + seconds_passed INLINECALLDICT // rdict ts + BALANCE // rdict ts _19 FIRST // rdict ts balance s0 s2 XCHG - 16 PUSHINT // balance ts rdict _19=16 + 32 PUSHINT // balance ts rdict _24=32 DICTIGETPREVEQ - NULLSWAPIFNOT2 // balance _29 _28 _30 + NULLSWAPIFNOT2 // balance _36 _35 _37 NIP // balance value found IF:<{ // balance value - LDGRAMS // balance _32 _31 - DROP // balance _21 - SUB // _23 - 0 PUSHINT // _23 _24=0 + LDGRAMS // balance _39 _38 + DROP // balance _26 + SUB // _28 + 0 PUSHINT // _28 _29=0 MAX // balance }>ELSE<{ DROP // balance }> }> + balance_at PROC:<{ + // utime + compute_balance_at INLINECALLDICT // _1 + }> + balance PROC:<{ + // + NOW // _0 + compute_balance_at INLINECALLDICT // _1 + }> }END>c diff --git a/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet3-code.cpp b/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet3-code.cpp new file mode 100644 index 00000000000..7b95f0b60ff --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet3-code.cpp @@ -0,0 +1 @@ +with_tvm_code("restricted-wallet3", "te6ccgECEgEAAUsAART/APSkE/S88sgLAQIBIAIDAgFIBAUD+PKDCNcYINMf0x/THwL4I7vyY+1E0NMf0x/T/1NDuvKhUWK68qIG+QFUEHb5EPKkAY4fMwHT/9EB0x/0BNH4AAOkyMsfFMsfy/8Syx/0AMntVOEC0x/0BNH4ACH4I9s8IYAg9HtvpTGW+gAwcvsCkTDiApMg10qK6NECpMgPEBEABNAwAgEgBgcCASAICQIBSAwNAgFuCgsAEbjJftRNDXCx+AAXrc52omhpn5jrhf/AABesePaiaGmPmOuFj8ABDbbYHwR7Z5AOAQm1B1tnkA4BTu1E0IEBQNch0x/0BNEC2zz4J28QAoAg9HtvpTGX+gAwoXC2CZEw4g8AOiGOETGA8/gzIG6SMHCU0NcLH+IB3yGSAaGSW3/iAAzTB9QC+wAAHssfFMsfEsv/yx/0AMntVA=="); diff --git a/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet3-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet3-code.fif new file mode 100644 index 00000000000..f84d3dcbcf9 --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/auto/restricted-wallet3-code.fif @@ -0,0 +1,199 @@ +// automatically generated from `smartcont/stdlib.fc` `smartcont/restricted-wallet3-code.fc` +PROGRAM{ + DECLPROC recv_internal + DECLPROC seconds_passed + DECLPROC recv_external + 85143 DECLMETHOD seqno + 80113 DECLMETHOD wallet_id + 78748 DECLMETHOD get_public_key + DECLPROC compute_balance_at + 108602 DECLMETHOD balance_at + 104128 DECLMETHOD balance + recv_internal PROC:<{ + // in_msg + DROP // + }> + seconds_passed PROCREF:<{ + // start_at utime + OVER // start_at utime start_at + IFNOT:<{ // start_at utime + NIP // utime + -13 PUSHINT // utime _3=-13 + CONFIGOPTPARAM // utime p + DUP // utime p p + ISNULL // utime p _5 + IF:<{ // utime p + DROP // utime + 0 PUSHINT // utime _6=0 + }>ELSE<{ // utime p + CTOS // utime _8 + 32 PLDU // utime _6 + }> // utime start_at + SWAP // start_at utime + }> // start_at utime + OVER // start_at utime start_at + IF:<{ // start_at utime + SWAP // utime start_at + SUB // _11 + }>ELSE<{ // start_at utime + 2DROP // + -1 PUSHINT // _11=-1 + }> + }> + recv_external PROC:<{ + // in_msg + 9 PUSHPOW2 // in_msg _3=512 + LDSLICEX // signature in_msg + DUP // signature in_msg cs + 32 LDU // signature in_msg _9 cs + 32 LDU // signature in_msg _9 _12 cs + 32 LDU // signature in_msg subwallet_id valid_until msg_seqno cs + s0 s2 XCHG + NOW // signature in_msg subwallet_id cs msg_seqno valid_until _19 + LEQ // signature in_msg subwallet_id cs msg_seqno _20 + 35 THROWIF + c4 PUSH // signature in_msg subwallet_id cs msg_seqno _23 + CTOS // signature in_msg subwallet_id cs msg_seqno ds + 32 LDU // signature in_msg subwallet_id cs msg_seqno _28 ds + 32 LDU // signature in_msg subwallet_id cs msg_seqno _28 _31 ds + 256 LDU // signature in_msg subwallet_id cs msg_seqno stored_seqno stored_subwallet public_key ds + s4 s3 PUSH2 // signature in_msg subwallet_id cs msg_seqno stored_seqno stored_subwallet public_key ds msg_seqno stored_seqno + EQUAL // signature in_msg subwallet_id cs msg_seqno stored_seqno stored_subwallet public_key ds _38 + 33 THROWIFNOT + s6 s2 XCPU // signature in_msg ds cs msg_seqno stored_seqno stored_subwallet public_key subwallet_id stored_subwallet + EQUAL // signature in_msg ds cs msg_seqno stored_seqno stored_subwallet public_key _41 + 34 THROWIFNOT + s0 s6 XCHG // signature public_key ds cs msg_seqno stored_seqno stored_subwallet in_msg + HASHSU // signature public_key ds cs msg_seqno stored_seqno stored_subwallet _44 + s0 s7 s6 XC2PU // stored_subwallet public_key ds cs msg_seqno stored_seqno _44 signature public_key + CHKSIGNU // stored_subwallet public_key ds cs msg_seqno stored_seqno _45 + 36 THROWIFNOT + SWAP // stored_subwallet public_key ds cs stored_seqno msg_seqno + IFNOTJMP:<{ // stored_subwallet public_key ds cs stored_seqno + s3 POP // stored_subwallet stored_seqno ds cs + SWAP // stored_subwallet stored_seqno cs ds + 256 LDU // stored_subwallet stored_seqno cs public_key ds + ENDS + SWAP // stored_subwallet stored_seqno public_key cs + 32 LDU // stored_subwallet stored_seqno public_key _55 cs + LDDICT // stored_subwallet stored_seqno public_key start_at rdict cs + ENDS + ACCEPT + s0 s3 XCHG // stored_subwallet rdict public_key start_at stored_seqno + INC // stored_subwallet rdict public_key start_at _63 + NEWC // stored_subwallet rdict public_key start_at _63 _64 + 32 STU // stored_subwallet rdict public_key start_at _66 + s1 s4 XCHG // start_at rdict public_key stored_subwallet _66 + 32 STU // start_at rdict public_key _68 + 256 STU // start_at rdict _70 + s1 s2 XCHG // rdict start_at _70 + 32 STU // rdict _72 + STDICT // _73 + ENDC // _74 + c4 POP + }> // stored_subwallet public_key ds cs stored_seqno + s0 s2 XCHG // stored_subwallet public_key stored_seqno cs ds + 32 LDU // stored_subwallet public_key stored_seqno cs _78 ds + LDDICT // stored_subwallet public_key stored_seqno cs start_at rdict ds + ENDS + ACCEPT + OVER + NOW // stored_subwallet public_key stored_seqno cs start_at rdict start_at _86 + seconds_passed INLINECALLDICT // stored_subwallet public_key stored_seqno cs start_at rdict ts + OVER + 32 PUSHINT // stored_subwallet public_key stored_seqno cs start_at rdict ts rdict _91=32 + DICTIGETPREVEQ + NULLSWAPIFNOT2 // stored_subwallet public_key stored_seqno cs start_at rdict _148 _147 _149 + NIP // stored_subwallet public_key stored_seqno cs start_at rdict value found + IF:<{ // stored_subwallet public_key stored_seqno cs start_at rdict value + LDGRAMS // stored_subwallet public_key stored_seqno cs start_at rdict _151 _150 + DROP // stored_subwallet public_key stored_seqno cs start_at rdict _93 + 2 PUSHINT // stored_subwallet public_key stored_seqno cs start_at rdict _93 _95=2 + RAWRESERVE + }>ELSE<{ + DROP // stored_subwallet public_key stored_seqno cs start_at rdict + }> + s0 s2 XCHG // stored_subwallet public_key stored_seqno rdict start_at cs + WHILE:<{ + DUP // stored_subwallet public_key stored_seqno rdict start_at cs cs + SREFS // stored_subwallet public_key stored_seqno rdict start_at cs _99 + }>DO<{ // stored_subwallet public_key stored_seqno rdict start_at cs + 8 LDU // stored_subwallet public_key stored_seqno rdict start_at mode cs + LDREF // stored_subwallet public_key stored_seqno rdict start_at mode msg cs + s0 s2 XCHG // stored_subwallet public_key stored_seqno rdict start_at cs msg mode + SENDRAWMSG + }> // stored_subwallet public_key stored_seqno rdict start_at cs + ENDS + s0 s2 XCHG // stored_subwallet public_key start_at rdict stored_seqno + INC // stored_subwallet public_key start_at rdict _110 + NEWC // stored_subwallet public_key start_at rdict _110 _111 + 32 STU // stored_subwallet public_key start_at rdict _113 + s1 s4 XCHG // rdict public_key start_at stored_subwallet _113 + 32 STU // rdict public_key start_at _115 + s1 s2 XCHG // rdict start_at public_key _115 + 256 STU // rdict start_at _117 + 32 STU // rdict _119 + STDICT // _120 + ENDC // _121 + c4 POP + }> + seqno PROC:<{ + // + c4 PUSH // _0 + CTOS // _1 + 32 PLDU // _3 + }> + wallet_id PROC:<{ + // + c4 PUSH // _1 + CTOS // ds + 32 LDU // _9 _8 + NIP // ds + 32 PLDU // _7 + }> + get_public_key PROC:<{ + // + c4 PUSH // _1 + CTOS // ds + 64 LDU // _11 _10 + NIP // ds + 256 PLDU // _9 + }> + compute_balance_at PROCREF:<{ + // utime + c4 PUSH // utime _2 + CTOS // utime _3 + 320 PUSHINT // utime _3 _8 + SDSKIPFIRST // utime ds + 32 LDU // utime _12 ds + LDDICT // utime start_at rdict ds + ENDS + s0 s2 XCHG // rdict start_at utime + seconds_passed INLINECALLDICT // rdict ts + BALANCE // rdict ts _21 + FIRST // rdict ts balance + s0 s2 XCHG + 32 PUSHINT // balance ts rdict _26=32 + DICTIGETPREVEQ + NULLSWAPIFNOT2 // balance _38 _37 _39 + NIP // balance value found + IF:<{ // balance value + LDGRAMS // balance _41 _40 + DROP // balance _28 + SUB // _30 + 0 PUSHINT // _30 _31=0 + MAX // balance + }>ELSE<{ + DROP // balance + }> + }> + balance_at PROC:<{ + // utime + compute_balance_at INLINECALLDICT // _1 + }> + balance PROC:<{ + // + NOW // _0 + compute_balance_at INLINECALLDICT // _1 + }> +}END>c diff --git a/submodules/ton/tonlib-src/crypto/smartcont/config-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/config-code.fif new file mode 100644 index 00000000000..1a4084fafe9 --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/config-code.fif @@ -0,0 +1,323 @@ +// automatically generated from `smartcont/stdlib.fc` `smartcont/config-code.fc` +PROGRAM{ + DECLPROC set_conf_param + DECLPROC check_validator_set + DECLPROC send_answer + DECLPROC send_confirmation + DECLPROC send_error + DECLPROC recv_internal + DECLPROC change_elector_code + DECLPROC recv_external + DECLPROC run_ticktock + set_conf_param PROC:<{ + // index value + c4 PUSH // index value _3 + CTOS // index value cs + LDREF // index value cfg_dict cs + s3 s3 XCHG2 + 32 PUSHINT // cs value index cfg_dict _9=32 + DICTISETREF // cs cfg_dict + NEWC // cs cfg_dict _11 + STREF // cs _12 + SWAP // _12 cs + STSLICER // _13 + ENDC // _14 + c4 POP + }> + check_validator_set PROC:<{ + // vset + CTOS // cs + 8 LDU // _4 cs + SWAP // cs _4 + 17 EQINT // cs _8 + 9 THROWIFNOT + 32 LDU // utime_since cs + 32 LDU // utime_since utime_until cs + 16 LDU // utime_since utime_until total cs + 16 LDU // utime_since utime_until total _42 _41 + DROP // utime_since utime_until total main + DUP // utime_since utime_until total main main + 0 GTINT // utime_since utime_until total main _28 + 9 THROWIFNOT + GEQ // utime_since utime_until _31 + 9 THROWIFNOT + }> + send_answer PROC:<{ + // addr query_id ans_tag mode + 0 PUSHINT // addr query_id ans_tag mode _4=0 + 24 PUSHINT // addr query_id ans_tag mode _4=0 _5=24 + NEWC // addr query_id ans_tag mode _4=0 _5=24 _6 + 6 STU // addr query_id ans_tag mode _4=0 _8 + s0 s5 XCHG2 // _4=0 query_id ans_tag mode _8 addr + STSLICER // _4=0 query_id ans_tag mode _9 + s1 s4 XCHG // mode query_id ans_tag _4=0 _9 + 111 STU // mode query_id ans_tag _23 + 32 STU // mode query_id _25 + 64 STU // mode _27 + ENDC // mode _28 + SWAP // _28 mode + SENDRAWMSG + }> + send_confirmation PROC:<{ + // addr query_id ans_tag + 64 PUSHINT // addr query_id ans_tag _3=64 + send_answer CALLDICT + }> + send_error PROC:<{ + // addr query_id ans_tag + 64 PUSHINT // addr query_id ans_tag _3=64 + send_answer CALLDICT + }> + recv_internal PROC:<{ + // in_msg_cell in_msg + SWAP // in_msg in_msg_cell + CTOS // in_msg cs + 4 LDU // in_msg flags cs + LDMSGADDR // in_msg flags _74 _73 + DROP // in_msg flags s_addr + DUP // in_msg flags s_addr s_addr + REWRITESTDADDR // in_msg flags s_addr src_wc src_addr + SWAP // in_msg flags s_addr src_addr src_wc + INC // in_msg flags s_addr src_addr _15 + s0 s3 XCHG + 1 PUSHINT // in_msg _15 s_addr src_addr flags _16=1 + AND // in_msg _15 s_addr src_addr _17 + s1 s3 XCHG // in_msg src_addr s_addr _15 _17 + OR // in_msg src_addr s_addr _18 + s3 PUSH // in_msg src_addr s_addr _18 in_msg + SEMPTY // in_msg src_addr s_addr _18 _19 + OR // in_msg src_addr s_addr _20 + IFJMP:<{ // in_msg src_addr s_addr + 3 BLKDROP // + }> // in_msg src_addr s_addr + s0 s2 XCHG // s_addr src_addr in_msg + 32 LDU // s_addr src_addr tag in_msg + 64 LDU // s_addr src_addr tag query_id in_msg + s2 PUSH + 1314280276 PUSHINT // s_addr src_addr tag query_id in_msg tag _29=1314280276 + EQUAL // s_addr src_addr tag query_id in_msg _30 + IFJMP:<{ // s_addr src_addr tag query_id in_msg + s2 POP // s_addr src_addr in_msg query_id + SWAP // s_addr src_addr query_id in_msg + LDREF // s_addr src_addr query_id vset in_msg + ENDS + 1 PUSHINT // s_addr src_addr query_id vset _36=1 + CONFIGOPTPARAM // s_addr src_addr query_id vset elector_param + DUP // s_addr src_addr query_id vset elector_param elector_param + ISNULL // s_addr src_addr query_id vset elector_param _39 + IF:<{ // s_addr src_addr query_id vset elector_param + DROP // s_addr src_addr query_id vset + -1 PUSHINT // s_addr src_addr query_id vset _40=-1 + }>ELSE<{ // s_addr src_addr query_id vset elector_param + CTOS // s_addr src_addr query_id vset _42 + 256 PLDU // s_addr src_addr query_id vset _40 + }> // s_addr src_addr query_id vset elector_addr + s0 s3 XCHG + FALSE + s0 s4 XCHG // s_addr ok query_id vset src_addr elector_addr + EQUAL // s_addr ok query_id vset _47 + IF:<{ // s_addr ok query_id vset + s2 POP // s_addr vset query_id + OVER // s_addr vset query_id vset + check_validator_set CALLDICT // s_addr vset query_id t_since t_until + OVER + NOW // s_addr vset query_id t_since t_until t_since t + GREATER // s_addr vset query_id t_since t_until _53 + s0 s2 XCHG // s_addr vset query_id _53 t_until t_since + GREATER // s_addr vset query_id _53 _54 + AND // s_addr vset query_id ok + }>ELSE<{ + s0 s2 XCHG // s_addr vset query_id ok + }> + IFJMP:<{ // s_addr vset query_id + 36 PUSHINT // s_addr vset query_id _56=36 + ROT // s_addr query_id _56=36 vset + set_conf_param CALLDICT + 4000730955 PUSHINT // s_addr query_id _58=4000730955 + send_confirmation CALLDICT + }> // s_addr vset query_id + NIP // s_addr query_id + 4000730991 PUSHINT // s_addr query_id _60=4000730991 + send_error CALLDICT + }> // s_addr src_addr tag query_id in_msg + s2 s4 XCHG + 4 BLKDROP // tag + DUP // tag tag + 0 EQINT // tag _64 + SWAP + 31 PUSHPOW2 // _64 tag _67 + AND // _64 _68 + OR // _69 + 37 THROWIFNOT + }> + change_elector_code PROC:<{ + // cs + 1 PUSHINT // cs _2=1 + CONFIGOPTPARAM // cs _3 + CTOS // cs _4 + 256 PLDU // cs dest_addr + NOW // cs dest_addr query_id + 1313042276 PUSHINT // cs dest_addr query_id _9=1313042276 + 0 PUSHINT // cs dest_addr query_id _9=1313042276 _10=0 + 50431 PUSHINT // cs dest_addr query_id _9=1313042276 _10=0 _11=50431 + NEWC // cs dest_addr query_id _9=1313042276 _10=0 _11=50431 _12 + 17 STU // cs dest_addr query_id _9=1313042276 _10=0 _14 + s1 s4 XCHG // cs _10=0 query_id _9=1313042276 dest_addr _14 + 256 STU // cs _10=0 query_id _9=1313042276 _16 + 30 PUSHPOW2 // cs _10=0 query_id _9=1313042276 _16 _19 + STGRAMS // cs _10=0 query_id _9=1313042276 _20 + s1 s3 XCHG // cs _9=1313042276 query_id _10=0 _20 + 107 STU // cs _9=1313042276 query_id _34 + s1 s2 XCHG // cs query_id _9=1313042276 _34 + 32 STU // cs query_id _36 + 64 STU // cs _38 + SWAP // _38 cs + STSLICER // _39 + ENDC // _40 + 0 PUSHINT // _40 _41=0 + SENDRAWMSG + }> + recv_external PROC:<{ + // in_msg + 9 PUSHPOW2 // in_msg _3=512 + LDSLICEX // signature in_msg + DUP // signature in_msg cs + 32 LDU // signature in_msg action cs + 32 LDU // signature in_msg action msg_seqno cs + 32 LDU // signature in_msg action msg_seqno valid_until cs + NOW // signature in_msg action msg_seqno valid_until cs _19 + s1 s2 XCHG // signature in_msg action msg_seqno cs valid_until _19 + LESS // signature in_msg action msg_seqno cs _20 + 35 THROWIF + c4 PUSH // signature in_msg action msg_seqno cs _23 + CTOS // signature in_msg action msg_seqno cs cs2 + LDREF // signature in_msg action msg_seqno cs cfg_dict cs2 + 32 LDU // signature in_msg action msg_seqno cs cfg_dict stored_seqno cs2 + 256 LDU // signature in_msg action msg_seqno cs cfg_dict stored_seqno public_key cs2 + ENDS + s4 s1 XCPU // signature in_msg action public_key cs cfg_dict stored_seqno msg_seqno stored_seqno + EQUAL // signature in_msg action public_key cs cfg_dict stored_seqno _38 + 33 THROWIFNOT + s0 s5 XCHG // signature stored_seqno action public_key cs cfg_dict in_msg + HASHSU // signature stored_seqno action public_key cs cfg_dict _41 + s0 s6 s3 XC2PU // cfg_dict stored_seqno action public_key cs _41 signature public_key + CHKSIGNU // cfg_dict stored_seqno action public_key cs _42 + 34 THROWIFNOT + ACCEPT + s2 PUSH + 1130778657 PUSHINT // cfg_dict stored_seqno action public_key cs action _45=1130778657 + EQUAL // cfg_dict stored_seqno action public_key cs _46 + IF:<{ // cfg_dict stored_seqno action public_key cs + s2 POP // cfg_dict stored_seqno cs public_key + SWAP // cfg_dict stored_seqno public_key cs + 32 LDU // cfg_dict stored_seqno public_key param_index cs + LDREF // cfg_dict stored_seqno public_key param_index param_value cs + ENDS + s0 s1 s4 XCHG3 + 32 PUSHINT // public_key stored_seqno param_value param_index cfg_dict _56=32 + DICTISETREF // public_key stored_seqno cfg_dict + }>ELSE<{ // cfg_dict stored_seqno action public_key cs + s2 PUSH + 1313042276 PUSHINT // cfg_dict stored_seqno action public_key cs action _58=1313042276 + EQUAL // cfg_dict stored_seqno action public_key cs _59 + IF:<{ // cfg_dict stored_seqno action public_key cs + s2 POP // cfg_dict stored_seqno cs public_key + SWAP // cfg_dict stored_seqno public_key cs + LDREF // cfg_dict stored_seqno public_key new_code cs + ENDS + SETCODE + }>ELSE<{ // cfg_dict stored_seqno action public_key cs + s2 PUSH + 1348619041 PUSHINT // cfg_dict stored_seqno action public_key cs action _65=1348619041 + EQUAL // cfg_dict stored_seqno action public_key cs _66 + IF:<{ // cfg_dict stored_seqno action public_key cs + NIP + NIP // cfg_dict stored_seqno cs + 256 LDU // cfg_dict stored_seqno public_key cs + ENDS + }>ELSE<{ // cfg_dict stored_seqno action public_key cs + s2 PUSH + 1313074949 PUSHINT // cfg_dict stored_seqno action public_key cs action _71=1313074949 + EQUAL // cfg_dict stored_seqno action public_key cs _72 + IF:<{ // cfg_dict stored_seqno action public_key cs + s2 POP // cfg_dict stored_seqno cs public_key + SWAP // cfg_dict stored_seqno public_key cs + change_elector_code CALLDICT + }>ELSE<{ // cfg_dict stored_seqno action public_key cs + DROP // cfg_dict stored_seqno action public_key + SWAP // cfg_dict stored_seqno public_key action + 32 THROWIF + }> + }> + }> + s0 s2 XCHG // public_key stored_seqno cfg_dict + }> + SWAP // public_key cfg_dict stored_seqno + INC // public_key cfg_dict _77 + NEWC // public_key cfg_dict _77 _78 + s1 s2 XCHG // public_key _77 cfg_dict _78 + STREF // public_key _77 _79 + 32 STU // public_key _81 + 256 STU // _83 + ENDC // _84 + c4 POP + }> + run_ticktock PROC:<{ + // is_tock + DROP // + c4 PUSH // _2 + CTOS // cs + LDREF // cfg_dict cs + 32 PUSHINT // cfg_dict cs kl=32 + 36 PUSHINT // cfg_dict cs kl=32 _10=36 + s3 s1 PUSH2 // cfg_dict cs kl=32 _10=36 cfg_dict kl=32 + DICTIGETOPTREF // cfg_dict cs kl=32 next_vset + DUP // cfg_dict cs kl=32 next_vset next_vset + ISNULL // cfg_dict cs kl=32 next_vset _12 + IFNOT:<{ // cfg_dict cs kl=32 next_vset + DUP // cfg_dict cs kl=32 next_vset next_vset + CTOS // cfg_dict cs kl=32 next_vset ds + DUP // cfg_dict cs kl=32 next_vset ds ds + SBITS // cfg_dict cs kl=32 next_vset ds _15 + 39 GTINT // cfg_dict cs kl=32 next_vset ds _17 + IF:<{ // cfg_dict cs kl=32 next_vset ds + 8 LDU // cfg_dict cs kl=32 next_vset tag ds + 32 PLDU // cfg_dict cs kl=32 next_vset tag since + SWAP // cfg_dict cs kl=32 next_vset since tag + 17 EQINT // cfg_dict cs kl=32 next_vset since _26 + NOW // cfg_dict cs kl=32 next_vset since _26 _27 + s1 s2 XCHG // cfg_dict cs kl=32 next_vset _26 since _27 + GEQ // cfg_dict cs kl=32 next_vset _26 _28 + AND // cfg_dict cs kl=32 next_vset _29 + IF:<{ // cfg_dict cs kl=32 next_vset + SWAP + 34 PUSHINT + s0 s4 s4 XC2PU // kl=32 cs next_vset _32=34 cfg_dict kl=32 + DICTISETGETOPTREF // kl=32 cs cfg_dict cur_vset + s3 s1 s0 PUXCPU // kl=32 cs cur_vset _35=32 cfg_dict kl=32 + DICTISETGETOPTREF // kl=32 cs _51 _52 + DROP // kl=32 cs cfg_dict + 36 PUSHINT // kl=32 cs cfg_dict _38=36 + s0 s1 s3 XCHG3 // cs _38=36 cfg_dict kl=32 + DICTIDEL // cs _53 _54 + DROP // cs cfg_dict + }>ELSE<{ + s2 s3 XCHG + 2DROP // cs cfg_dict + }> + }>ELSE<{ + s3 s4 XCHG + 3 BLKDROP // cs cfg_dict + }> + }>ELSE<{ + s2 s3 XCHG + 2DROP // cs cfg_dict + }> + NEWC // cs cfg_dict _40 + STREF // cs _41 + SWAP // _41 cs + STSLICER // _42 + ENDC // _43 + c4 POP + }> +}END>c diff --git a/submodules/ton/tonlib-src/crypto/smartcont/elector-code.fc b/submodules/ton/tonlib-src/crypto/smartcont/elector-code.fc index 33436800486..203275f34ef 100644 --- a/submodules/ton/tonlib-src/crypto/smartcont/elector-code.fc +++ b/submodules/ton/tonlib-src/crypto/smartcont/elector-code.fc @@ -1097,8 +1097,21 @@ tuple past_elections() method_id { do { (id, var fs, var found) = past_elections.udict_get_prev?(32, id); if (found) { - var info = [unpack_past_election(fs)]; - list = cons(pair(id, info), list); + list = cons([id, unpack_past_election(fs)], list); + } + } until (~ found); + return list; +} + +tuple past_elections_list() method_id { + var (elect, credits, past_elections, grams, active_id, active_hash) = load_data(); + var id = (1 << 32); + var list = null(); + do { + (id, var fs, var found) = past_elections.udict_get_prev?(32, id); + if (found) { + var (unfreeze_at, stake_held, vset_hash, frozen_dict, total_stake, bonuses, complaints) = unpack_past_election(fs); + list = cons([id, unfreeze_at, vset_hash, stake_held], list); } } until (~ found); return list; diff --git a/submodules/ton/tonlib-src/crypto/smartcont/elector-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/elector-code.fif new file mode 100644 index 00000000000..d964063b2eb --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/elector-code.fif @@ -0,0 +1,1712 @@ +// automatically generated from `smartcont/stdlib.fc` `smartcont/elector-code.fc` +PROGRAM{ + DECLPROC load_data + DECLPROC store_data + DECLPROC unpack_elect + DECLPROC pack_elect + DECLPROC get_validator_conf + DECLPROC send_message_back + DECLPROC return_stake + DECLPROC send_confirmation + DECLPROC send_validator_set_to_config + DECLPROC ~credit_to + DECLPROC process_new_stake + DECLPROC unfreeze_without_bonuses + DECLPROC unfreeze_with_bonuses + DECLPROC unfreeze_all + DECLPROC config_set_confirmed + DECLPROC process_simple_transfer + DECLPROC recover_stake + 1666 DECLMETHOD after_code_upgrade + DECLPROC upgrade_code + DECLPROC recv_internal + DECLPROC postpone_elections + DECLPROC compute_total_stake + DECLPROC try_elect + DECLPROC conduct_elections + DECLPROC update_active_vset_id + DECLPROC cell_hash_eq? + DECLPROC validator_set_installed + DECLPROC check_unfreeze + DECLPROC announce_new_elections + DECLPROC run_ticktock + 86535 DECLMETHOD active_election_id + 87852 DECLMETHOD participates_in + 123541 DECLMETHOD participant_list + 130944 DECLMETHOD compute_returned_stake + load_data PROC:<{ + // + c4 PUSH // _1 + CTOS // cs + LDDICT // _4 cs + LDDICT // _4 _6 cs + LDDICT // _4 _6 _8 cs + LDGRAMS // _4 _6 _8 _10 cs + 32 LDU // _4 _6 _8 _10 _12 cs + 256 LDU // res res res res res res cs + ENDS + }> + store_data PROC:<{ + // elect credits past_elect grams active_id active_hash + NEWC // elect credits past_elect grams active_id active_hash _6 + s1 s6 XCHG // active_hash credits past_elect grams active_id elect _6 + STDICT // active_hash credits past_elect grams active_id _7 + s1 s4 XCHG // active_hash active_id past_elect grams credits _7 + STDICT // active_hash active_id past_elect grams _8 + s1 s2 XCHG // active_hash active_id grams past_elect _8 + STDICT // active_hash active_id grams _9 + SWAP // active_hash active_id _9 grams + STGRAMS // active_hash active_id _10 + 32 STU // active_hash _12 + 256 STU // _14 + ENDC // _15 + c4 POP + }> + unpack_elect PROC:<{ + // elect + CTOS // es + 32 LDU // _4 es + 32 LDU // _4 _7 es + LDGRAMS // _4 _7 _10 es + LDGRAMS // _4 _7 _10 _12 es + LDDICT // _4 _7 _10 _12 _14 es + 1 LDI // _4 _7 _10 _12 _14 _16 es + 1 LDI // res res res res res res res es + ENDS + }> + pack_elect PROC:<{ + // elect_at elect_close min_stake total_stake members failed finished + NEWC // elect_at elect_close min_stake total_stake members failed finished _7 + s1 s7 XCHG // finished elect_close min_stake total_stake members failed elect_at _7 + 32 STU // finished elect_close min_stake total_stake members failed _9 + s1 s5 XCHG // finished failed min_stake total_stake members elect_close _9 + 32 STU // finished failed min_stake total_stake members _11 + s0 s3 XCHG2 // finished failed members total_stake _11 min_stake + STGRAMS // finished failed members total_stake _12 + SWAP // finished failed members _12 total_stake + STGRAMS // finished failed members _13 + STDICT // finished failed _14 + 1 STI // finished _16 + 1 STI // _18 + ENDC // _19 + }> + get_validator_conf PROC:<{ + // + 15 PUSHINT // _1=15 + CONFIGOPTPARAM // _2 + CTOS // cs + 32 LDI // _4 cs + 32 LDI // _4 _7 cs + 32 LDI // _4 _7 _10 cs + 32 PLDI // _4 _7 _10 _14 + }> + send_message_back PROC:<{ + // addr ans_tag query_id body grams mode + 0 PUSHINT // addr ans_tag query_id body grams mode _7=0 + 24 PUSHINT // addr ans_tag query_id body grams mode _7=0 _8=24 + NEWC // addr ans_tag query_id body grams mode _7=0 _8=24 _9 + 6 STU // addr ans_tag query_id body grams mode _7=0 _11 + s0 s7 XCHG2 // _7=0 ans_tag query_id body grams mode _11 addr + STSLICER // _7=0 ans_tag query_id body grams mode _12 + ROT // _7=0 ans_tag query_id body mode _12 grams + STGRAMS // _7=0 ans_tag query_id body mode _13 + s1 s5 XCHG // mode ans_tag query_id body _7=0 _13 + 107 STU // mode ans_tag query_id body _27 + s1 s3 XCHG // mode body query_id ans_tag _27 + 32 STU // mode body query_id _29 + 64 STU // mode body msg + OVER // mode body msg body + -1 GTINT // mode body msg _33 + IF:<{ // mode body msg + 32 STU // mode msg + }>ELSE<{ + NIP // mode msg + }> + ENDC // mode _37 + SWAP // _37 mode + SENDRAWMSG + }> + return_stake PROC:<{ + // addr query_id reason + 4000269644 PUSHINT // addr query_id reason _3=4000269644 + 0 PUSHINT // addr query_id reason _3=4000269644 _4=0 + s3 s3 s0 XCHG3 + 64 PUSHINT // addr _3=4000269644 query_id reason _4=0 _5=64 + send_message_back CALLDICT + }> + send_confirmation PROC:<{ + // addr query_id comment + 4084484172 PUSHINT // addr query_id comment _3=4084484172 + 1000000000 PUSHINT // addr query_id comment _3=4084484172 _4=1000000000 + s3 s3 s0 XCHG3 + 2 PUSHINT // addr _3=4084484172 query_id comment _4=1000000000 _5=2 + send_message_back CALLDICT + }> + send_validator_set_to_config PROC:<{ + // config_addr vset query_id + 1314280276 PUSHINT // config_addr vset query_id _4=1314280276 + 0 PUSHINT // config_addr vset query_id _4=1314280276 _5=0 + 50431 PUSHINT // config_addr vset query_id _4=1314280276 _5=0 _6=50431 + NEWC // config_addr vset query_id _4=1314280276 _5=0 _6=50431 _7 + 17 STU // config_addr vset query_id _4=1314280276 _5=0 _9 + s1 s5 XCHG // _5=0 vset query_id _4=1314280276 config_addr _9 + 256 STU // _5=0 vset query_id _4=1314280276 _11 + 30 PUSHPOW2 // _5=0 vset query_id _4=1314280276 _11 _14 + STGRAMS // _5=0 vset query_id _4=1314280276 _15 + s1 s4 XCHG // _4=1314280276 vset query_id _5=0 _15 + 107 STU // _4=1314280276 vset query_id _29 + s1 s3 XCHG // query_id vset _4=1314280276 _29 + 32 STU // query_id vset _31 + s1 s2 XCHG // vset query_id _31 + 64 STU // vset _33 + STREF // msg + ENDC // _35 + 1 PUSHINT // _35 _36=1 + SENDRAWMSG + }> + ~credit_to PROC:<{ + // credits addr amount + s1 s2 PUSH2 + 8 PUSHPOW2 // credits addr amount addr credits _5=256 + DICTUGET + NULLSWAPIFNOT // credits addr amount val f + IF:<{ // credits addr amount val + LDGRAMS // credits addr amount _18 _17 + DROP // credits addr amount _7 + ADD // credits addr amount + }>ELSE<{ + DROP // credits addr amount + }> + NEWC // credits addr amount _11 + SWAP // credits addr _11 amount + STGRAMS // credits addr _12 + s0 s2 XCHG + 8 PUSHPOW2 // _12 addr credits _13=256 + DICTUSETB // credits + }> + process_new_stake PROC:<{ + // s_addr msg_value cs query_id + s3 PUSH // s_addr msg_value cs query_id s_addr + REWRITESTDADDR // s_addr msg_value cs query_id src_wc src_addr + c4 PUSH // s_addr msg_value cs query_id src_wc src_addr _8 + CTOS // s_addr msg_value cs query_id src_wc src_addr ds + LDDICT // s_addr msg_value cs query_id src_wc src_addr elect ds + OVER // s_addr msg_value cs query_id src_wc src_addr elect ds elect + ISNULL // s_addr msg_value cs query_id src_wc src_addr elect ds _13 + s0 s4 XCHG // s_addr msg_value cs query_id _13 src_addr elect ds src_wc + INC // s_addr msg_value cs query_id _13 src_addr elect ds _15 + s1 s4 XCHG // s_addr msg_value cs query_id ds src_addr elect _13 _15 + OR // s_addr msg_value cs query_id ds src_addr elect _16 + IFJMP:<{ // s_addr msg_value cs query_id ds src_addr elect + s3 s5 XCHG + 5 BLKDROP // s_addr query_id + 0 PUSHINT // s_addr query_id _17=0 + return_stake CALLDICT + }> // s_addr msg_value cs query_id ds src_addr elect + s0 s4 XCHG // s_addr msg_value elect query_id ds src_addr cs + 256 LDU // s_addr msg_value elect query_id ds src_addr validator_pubkey cs + 32 LDU // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at cs + 32 LDU // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor cs + 256 LDU // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr cs + LDREF // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr _36 cs + SWAP // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr cs _36 + CTOS // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr cs _38 + 9 PUSHPOW2 // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr cs _38 _39=512 + PLDSLICEX // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr cs signature + SWAP // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature cs + ENDS + 1699500148 PUSHINT // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature _42=1699500148 + NEWC // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature _42=1699500148 _43 + 32 STU // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature _45 + s4 s(-1) PUXC // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature stake_at _45 + 32 STU // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature _47 + s3 s(-1) PUXC // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature max_factor _47 + 32 STU // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature _49 + s6 s(-1) PUXC // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature src_addr _49 + 256 STU // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature _51 + s2 s(-1) PUXC // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature adnl_addr _51 + 256 STU // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature _53 + ENDC // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature _54 + CTOS // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr signature _55 + s1 s5 XCPU // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr _55 signature validator_pubkey + CHKSIGNS // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr _56 + IFNOTJMP:<{ // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr + s6 s8 XCHG + 8 BLKDROP // s_addr query_id + 1 PUSHINT // s_addr query_id _57=1 + return_stake CALLDICT + }> // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr + OVER + 16 PUSHPOW2 // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr max_factor _59=65536 + LESS // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr _60 + IFJMP:<{ // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr + s6 s8 XCHG + 8 BLKDROP // s_addr query_id + 6 PUSHINT // s_addr query_id _61=6 + return_stake CALLDICT + }> // s_addr msg_value elect query_id ds src_addr validator_pubkey stake_at max_factor adnl_addr + s0 s7 XCHG // s_addr msg_value adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor elect + unpack_elect CALLDICT // s_addr msg_value adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor _146 _147 _148 _149 _150 _151 _152 + NIP // s_addr msg_value adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor elect_at elect_close min_stake total_stake members finished + s0 s5 XCHG // s_addr msg_value adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members elect_at + s0 DUMP // s_addr msg_value adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members elect_at + s0 s13 XCHG + 1000000000 PUSHINT // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members msg_value _73=1000000000 + SUB // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members msg_value + DUP // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members msg_value msg_value + 12 LSHIFT# // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members msg_value _76 + s3 PUSH // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members msg_value _76 total_stake + LESS // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members msg_value _77 + IFJMP:<{ // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members msg_value + s11 s12 XCHG + 12 BLKDROP + NIP // s_addr query_id + 2 PUSHINT // s_addr query_id _78=2 + return_stake CALLDICT + }> // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake total_stake members msg_value + s2 s2 XCPU // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake msg_value members total_stake msg_value + ADD // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey stake_at max_factor finished elect_close min_stake msg_value members total_stake + s7 s13 XCPU // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor finished elect_close min_stake msg_value members stake_at elect_at + NEQ // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor finished elect_close min_stake msg_value members _81 + IFJMP:<{ // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor finished elect_close min_stake msg_value members + s10 s12 XCHG + 12 BLKDROP // s_addr query_id + 3 PUSHINT // s_addr query_id _82=3 + return_stake CALLDICT + }> // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor finished elect_close min_stake msg_value members + s0 s4 XCHG // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value finished + IFJMP:<{ // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value + s9 s11 XCHG + 11 BLKDROP // s_addr query_id + 0 PUSHINT // s_addr query_id _84=0 + return_stake CALLDICT + }> // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value + s6 s3 PUSH2 + 8 PUSHPOW2 // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value validator_pubkey members _88=256 + DICTUGET + NULLSWAPIFNOT // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value mem found + DUP // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value mem found found + IF:<{ // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value mem found + DROP // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value mem + LDGRAMS // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value _90 mem + -ROT // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake mem msg_value _90 + ADD // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake mem msg_value + SWAP // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value mem + 64 LDU // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value _158 _157 + NIP // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value mem + 256 LDU // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value _160 _159 + DROP // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value _96 + s8 s(-1) PUXC // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value src_addr _96 + NEQ // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value found + }>ELSE<{ + NIP // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value found + }> + IFJMP:<{ // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value + s9 s11 XCHG + 11 BLKDROP // s_addr query_id + 4 PUSHINT // s_addr query_id _100=4 + return_stake CALLDICT + }> // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value + s0 s1 PUSH2 // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value msg_value min_stake + LESS // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value _102 + IFJMP:<{ // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value + s9 s11 XCHG + 11 BLKDROP // s_addr query_id + 5 PUSHINT // s_addr query_id _103=5 + return_stake CALLDICT + }> // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value + DUP // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value msg_value + 44 THROWIFNOT + ACCEPT + NOW // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value _109 + NEWC // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake msg_value _109 _110 + ROT // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake _109 _110 msg_value + STGRAMS // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake _109 _111 + 32 STU // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake max_factor members elect_close min_stake _113 + s1 s4 XCHG // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake min_stake members elect_close max_factor _113 + 32 STU // s_addr elect_at adnl_addr query_id ds src_addr validator_pubkey total_stake min_stake members elect_close _115 + s1 s6 XCHG // s_addr elect_at adnl_addr query_id ds elect_close validator_pubkey total_stake min_stake members src_addr _115 + 256 STU // s_addr elect_at adnl_addr query_id ds elect_close validator_pubkey total_stake min_stake members _117 + s1 s8 XCHG // s_addr elect_at members query_id ds elect_close validator_pubkey total_stake min_stake adnl_addr _117 + 256 STU // s_addr elect_at members query_id ds elect_close validator_pubkey total_stake min_stake _119 + s0 s3 s7 XCHG3 + 8 PUSHPOW2 // s_addr elect_at total_stake query_id ds elect_close min_stake _119 validator_pubkey members _120=256 + DICTUSETB // s_addr elect_at total_stake query_id ds elect_close min_stake members + FALSE // s_addr elect_at total_stake query_id ds elect_close min_stake members _122 + s5 s7 XCHG + s3 s4 XCHG + s2 s3 XCHG + s2 s6 XCHG + FALSE // s_addr query_id ds elect_at elect_close min_stake total_stake members _122 _123 + pack_elect CALLDICT // s_addr query_id ds elect + NEWC // s_addr query_id ds elect _125 + STDICT // s_addr query_id ds _126 + SWAP // s_addr query_id _126 ds + STSLICER // s_addr query_id _127 + ENDC // s_addr query_id _128 + c4 POP + DUP // s_addr query_id query_id + IFJMP:<{ // s_addr query_id + 0 PUSHINT // s_addr query_id _130=0 + send_confirmation CALLDICT + }> // s_addr query_id + 2DROP // + }> + unfreeze_without_bonuses PROC:<{ + // credits freeze_dict tot_stakes + 0 PUSHINT // credits freeze_dict tot_stakes _5=0 + DUP // credits freeze_dict tot_stakes total=0 recovered=0 + -1 PUSHINT // credits freeze_dict tot_stakes total=0 recovered=0 pubkey=-1 + UNTIL:<{ + s4 PUSH + 8 PUSHPOW2 // credits freeze_dict tot_stakes total recovered pubkey freeze_dict _10=256 + DICTUGETNEXT + NULLSWAPIFNOT + NULLSWAPIFNOT // credits freeze_dict tot_stakes total recovered cs pubkey f + DUP // credits freeze_dict tot_stakes total recovered cs pubkey f f + IF:<{ // credits freeze_dict tot_stakes total recovered cs pubkey f + s0 s2 XCHG // credits freeze_dict tot_stakes total recovered f pubkey cs + 256 LDU // credits freeze_dict tot_stakes total recovered f pubkey _16 cs + 64 LDU // credits freeze_dict tot_stakes total recovered f pubkey _16 _42 _41 + NIP // credits freeze_dict tot_stakes total recovered f pubkey _16 cs + LDGRAMS // credits freeze_dict tot_stakes total recovered f pubkey _16 _22 cs + 1 LDI // credits freeze_dict tot_stakes total recovered f pubkey addr stake banned cs + ENDS + IF:<{ // credits freeze_dict tot_stakes total recovered f pubkey addr stake + NIP // credits freeze_dict tot_stakes total recovered f pubkey stake + s3 s3 XCPU // credits freeze_dict tot_stakes total stake f pubkey recovered stake + ADD // credits freeze_dict tot_stakes total stake f pubkey recovered + }>ELSE<{ // credits freeze_dict tot_stakes total recovered f pubkey addr stake + s8 s8 s8 XC2PU // stake freeze_dict tot_stakes total recovered f pubkey credits addr stake + ~credit_to CALLDICT // stake freeze_dict tot_stakes total recovered f pubkey credits + s0 s7 XCHG + s0 s3 XCHG // credits freeze_dict tot_stakes total stake f pubkey recovered + }> + s4 s3 XCHG2 // credits freeze_dict tot_stakes pubkey recovered f total stake + ADD // credits freeze_dict tot_stakes pubkey recovered f total + }>ELSE<{ + s4 s2 XCHG2 + DROP // credits freeze_dict tot_stakes pubkey recovered f total + }> + SWAP // credits freeze_dict tot_stakes pubkey recovered total f + NOT // credits freeze_dict tot_stakes pubkey recovered total _32 + s1 s3 XCHG // credits freeze_dict tot_stakes total recovered pubkey _32 + }> // credits freeze_dict tot_stakes total recovered pubkey + DROP + s3 POP // credits recovered tot_stakes total + SWAP // credits recovered total tot_stakes + EQUAL // credits recovered _34 + 59 THROWIFNOT + }> + unfreeze_with_bonuses PROC:<{ + // credits freeze_dict tot_stakes tot_bonuses + 0 PUSHINT // credits freeze_dict tot_stakes tot_bonuses _7=0 + s0 s0 PUSH2 // credits freeze_dict tot_stakes tot_bonuses total=0 returned_bonuses=0 recovered=0 + -1 PUSHINT // credits freeze_dict tot_stakes tot_bonuses total=0 returned_bonuses=0 recovered=0 pubkey=-1 + UNTIL:<{ + s6 PUSH + 8 PUSHPOW2 // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered pubkey freeze_dict _12=256 + DICTUGETNEXT + NULLSWAPIFNOT + NULLSWAPIFNOT // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered cs pubkey f + DUP // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered cs pubkey f f + IF:<{ // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered cs pubkey f + s0 s2 XCHG // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey cs + 256 LDU // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey _18 cs + 64 LDU // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey _18 _52 _51 + NIP // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey _18 cs + LDGRAMS // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey _18 _24 cs + 1 LDI // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey addr stake banned cs + ENDS + IF:<{ // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey addr stake + NIP // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey stake + s3 s3 XCPU // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses stake f pubkey recovered stake + ADD // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses stake f pubkey recovered + }>ELSE<{ // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey addr stake + s7 s0 s8 PUSH3 // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey addr stake tot_bonuses stake tot_stakes + MULDIV // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey addr stake bonus + s6 s6 XCPU // credits freeze_dict tot_stakes tot_bonuses total bonus recovered f pubkey addr stake returned_bonuses bonus + ADD // credits freeze_dict tot_stakes tot_bonuses total bonus recovered f pubkey addr stake returned_bonuses + s1 s6 PUXC // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey addr stake stake bonus + ADD // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey addr stake _35 + s11 s11 s0 XCHG3 // stake freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey credits addr _35 + ~credit_to CALLDICT // stake freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered f pubkey credits + s0 s9 XCHG + s0 s3 XCHG // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses stake f pubkey recovered + }> + s5 s3 XCHG2 // credits freeze_dict tot_stakes tot_bonuses pubkey returned_bonuses recovered f total stake + ADD // credits freeze_dict tot_stakes tot_bonuses pubkey returned_bonuses recovered f total + }>ELSE<{ + s5 s2 XCHG2 + DROP // credits freeze_dict tot_stakes tot_bonuses pubkey returned_bonuses recovered f total + }> + SWAP // credits freeze_dict tot_stakes tot_bonuses pubkey returned_bonuses recovered total f + NOT // credits freeze_dict tot_stakes tot_bonuses pubkey returned_bonuses recovered total _38 + s1 s4 XCHG // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered pubkey _38 + }> // credits freeze_dict tot_stakes tot_bonuses total returned_bonuses recovered pubkey + DROP + s5 POP // credits recovered tot_stakes tot_bonuses total returned_bonuses + s0 s3 XCHG // credits recovered returned_bonuses tot_bonuses total tot_stakes + EQUAL // credits recovered returned_bonuses tot_bonuses _40 + s2 s1 PUSH2 // credits recovered returned_bonuses tot_bonuses _40 returned_bonuses tot_bonuses + LEQ // credits recovered returned_bonuses tot_bonuses _40 _41 + AND // credits recovered returned_bonuses tot_bonuses _42 + 59 THROWIFNOT + s1 s2 XCHG // credits returned_bonuses recovered tot_bonuses + ADD // credits returned_bonuses _44 + SWAP // credits _44 returned_bonuses + SUB // credits _45 + }> + unfreeze_all PROC:<{ + // credits past_elections elect_id + SWAP + 32 PUSHINT // credits elect_id past_elections _6=32 + DICTUDELGET + NULLSWAPIFNOT // credits past_elections fs f + IFNOTJMP:<{ // credits past_elections fs + DROP // credits past_elections + 0 PUSHINT // credits past_elections _8=0 + }> // credits past_elections fs + 64 LDU // credits past_elections _44 _43 + NIP // credits past_elections fs + 256 LDU // credits past_elections _46 _45 + NIP // credits past_elections fs + LDDICT // credits past_elections _21 fs + LDGRAMS // credits past_elections _21 _23 fs + LDGRAMS // credits past_elections _21 _23 _25 fs + LDDICT // credits past_elections _21 _23 _25 _54 _53 + NIP // credits past_elections fdict tot_stakes bonuses fs + ENDS + DUP // credits past_elections fdict tot_stakes bonuses bonuses + 0 GTINT // credits past_elections fdict tot_stakes bonuses _32 + IF:<{ // credits past_elections fdict tot_stakes bonuses + s3 s4 XCHG // past_elections credits fdict tot_stakes bonuses + unfreeze_with_bonuses CALLDICT // past_elections credits _33 + }>ELSE<{ // credits past_elections fdict tot_stakes bonuses + DROP // credits past_elections fdict tot_stakes + s2 s3 XCHG // past_elections credits fdict tot_stakes + unfreeze_without_bonuses CALLDICT // past_elections credits _33 + }> // past_elections credits unused_prizes + s1 s2 XCHG // credits past_elections unused_prizes + }> + config_set_confirmed PROC:<{ + // s_addr cs query_id ok + s2 POP // s_addr ok query_id + s0 s2 XCHG // query_id ok s_addr + REWRITESTDADDR // query_id ok src_wc src_addr + 0 PUSHINT // query_id ok src_wc src_addr _8=0 + CONFIGOPTPARAM // query_id ok src_wc src_addr _9 + CTOS // query_id ok src_wc src_addr _10 + 256 PLDU // query_id ok src_wc src_addr config_addr + c4 PUSH // query_id ok src_wc src_addr config_addr _14 + CTOS // query_id ok src_wc src_addr config_addr ds + LDDICT // query_id ok src_wc src_addr config_addr elect ds + s0 s4 XCHG // query_id ok ds src_addr config_addr elect src_wc + INC // query_id ok ds src_addr config_addr elect _20 + 2SWAP // query_id ok ds elect _20 src_addr config_addr + NEQ // query_id ok ds elect _20 _21 + OR // query_id ok ds elect _22 + OVER // query_id ok ds elect _22 elect + ISNULL // query_id ok ds elect _22 _23 + OR // query_id ok ds elect _24 + IFJMP:<{ // query_id ok ds elect + 4 BLKDROP // + }> // query_id ok ds elect + unpack_elect CALLDICT // query_id ok ds _63 _64 _65 _66 _67 _68 _69 + s0 s5 XCHG + 5 BLKDROP // query_id ok ds elect_at finished + s1 s4 PUXC // finished ok ds elect_at elect_at query_id + NEQ // finished ok ds elect_at _33 + s0 s4 XCHG // _33 ok ds elect_at finished + NOT // _33 ok ds elect_at _34 + s1 s4 XCHG // elect_at ok ds _33 _34 + OR // elect_at ok ds _35 + IFJMP:<{ // elect_at ok ds + 3 BLKDROP // + }> // elect_at ok ds + ACCEPT + SWAP // elect_at ds ok + IFNOT:<{ // elect_at ds + LDDICT // elect_at _40 ds + LDDICT // elect_at _40 _42 ds + LDGRAMS // elect_at credits past_elections grams ds + s3 s3 s4 XCHG3 // ds grams credits past_elections elect_at + unfreeze_all CALLDICT // ds grams credits past_elections unused_prizes + FALSE // ds grams credits past_elections unused_prizes _48 + NEWC // ds grams credits past_elections unused_prizes _48 _49 + 1 STI // ds grams credits past_elections unused_prizes _51 + s1 s3 XCHG // ds grams unused_prizes past_elections credits _51 + STDICT // ds grams unused_prizes past_elections _52 + STDICT // ds grams unused_prizes _53 + -ROT // ds _53 grams unused_prizes + ADD // ds _53 _54 + STGRAMS // ds _55 + SWAP // _55 ds + STSLICER // _56 + ENDC // _57 + c4 POP + }>ELSE<{ + 2DROP // + }> + }> + process_simple_transfer PROC:<{ + // s_addr msg_value + load_data CALLDICT // s_addr msg_value elect credits past_elect grams active_id active_hash + s0 s7 XCHG // active_hash msg_value elect credits past_elect grams active_id s_addr + REWRITESTDADDR // active_hash msg_value elect credits past_elect grams active_id src_wc src_addr + SWAP // active_hash msg_value elect credits past_elect grams active_id src_addr src_wc + INC // active_hash msg_value elect credits past_elect grams active_id src_addr _13 + OR // active_hash msg_value elect credits past_elect grams active_id _14 + OVER // active_hash msg_value elect credits past_elect grams active_id _14 active_id + 0 EQINT // active_hash msg_value elect credits past_elect grams active_id _14 _16 + OR // active_hash msg_value elect credits past_elect grams active_id _17 + IFJMP:<{ // active_hash msg_value elect credits past_elect grams active_id + s0 s5 XCHG // active_hash active_id elect credits past_elect grams msg_value + ADD // active_hash active_id elect credits past_elect grams + 2 4 BLKSWAP + SWAP // elect credits past_elect grams active_id active_hash + store_data CALLDICT + }> // active_hash msg_value elect credits past_elect grams active_id + s0 s2 PUSH2 + 32 PUSHINT // active_hash msg_value elect credits past_elect grams active_id active_id past_elect _22=32 + DICTUGET + NULLSWAPIFNOT // active_hash msg_value elect credits past_elect grams active_id fs f + IF:<{ // active_hash msg_value elect credits past_elect grams active_id fs + 64 LDU // active_hash msg_value elect credits past_elect grams active_id _30 fs + 256 LDU // active_hash msg_value elect credits past_elect grams active_id _30 _33 fs + LDDICT // active_hash msg_value elect credits past_elect grams active_id _30 _33 _36 fs + LDGRAMS // active_hash msg_value elect credits past_elect grams active_id _30 _33 _36 _38 fs + LDGRAMS // active_hash msg_value elect credits past_elect grams active_id data hash dict total_stake bonuses fs + s0 s11 XCHG // active_hash fs elect credits past_elect grams active_id data hash dict total_stake bonuses msg_value + ADD // active_hash fs elect credits past_elect grams active_id data hash dict total_stake bonuses + NEWC // active_hash fs elect credits past_elect grams active_id data hash dict total_stake bonuses _44 + s1 s5 XCHG // active_hash fs elect credits past_elect grams active_id bonuses hash dict total_stake data _44 + 64 STU // active_hash fs elect credits past_elect grams active_id bonuses hash dict total_stake _46 + s1 s3 XCHG // active_hash fs elect credits past_elect grams active_id bonuses total_stake dict hash _46 + 256 STU // active_hash fs elect credits past_elect grams active_id bonuses total_stake dict _48 + STDICT // active_hash fs elect credits past_elect grams active_id bonuses total_stake _49 + SWAP // active_hash fs elect credits past_elect grams active_id bonuses _49 total_stake + STGRAMS // active_hash fs elect credits past_elect grams active_id bonuses _50 + SWAP // active_hash fs elect credits past_elect grams active_id _50 bonuses + STGRAMS // active_hash fs elect credits past_elect grams active_id _51 + s0 s6 XCHG2 // active_hash active_id elect credits past_elect grams _51 fs + STSLICER // active_hash active_id elect credits past_elect grams _52 + SWAP + 32 PUSHINT + s6 s3 s3 PUXC2 // active_hash active_id elect credits grams _52 active_id past_elect _53=32 + DICTUSETB // active_hash active_id elect credits grams past_elect + }>ELSE<{ // active_hash msg_value elect credits past_elect grams active_id fs + DROP // active_hash msg_value elect credits past_elect grams active_id + s0 s5 XCHG // active_hash active_id elect credits past_elect grams msg_value + ADD // active_hash active_id elect credits past_elect grams + SWAP // active_hash active_id elect credits grams past_elect + }> + s3 s5 XCHG + s1 s4 s3 XCHG3 // elect credits past_elect grams active_id active_hash + store_data CALLDICT + }> + recover_stake PROC:<{ + // op s_addr cs query_id + NIP // op s_addr query_id + OVER // op s_addr query_id s_addr + REWRITESTDADDR // op s_addr query_id src_wc src_addr + SWAP // op s_addr query_id src_addr src_wc + INC // op s_addr query_id src_addr _8 + IFJMP:<{ // op s_addr query_id src_addr + DROP // op s_addr query_id + 4294967294 PUSHINT // op s_addr query_id _9=4294967294 + 0 PUSHINT // op s_addr query_id _9=4294967294 _10=0 + s3 s4 XCHG + s1 s3 XCHG + 64 PUSHINT // s_addr _9=4294967294 query_id op _10=0 _11=64 + send_message_back CALLDICT + }> // op s_addr query_id src_addr + c4 PUSH // op s_addr query_id src_addr _14 + CTOS // op s_addr query_id src_addr ds + LDDICT // op s_addr query_id src_addr _18 ds + LDDICT // op s_addr query_id src_addr elect credits ds + s3 s3 XCHG2 + 8 PUSHPOW2 // op s_addr query_id ds elect src_addr credits _25=256 + DICTUDELGET + NULLSWAPIFNOT // op s_addr query_id ds elect credits cs f + IFNOTJMP:<{ // op s_addr query_id ds elect credits cs + 4 BLKDROP // op s_addr query_id + 4294967294 PUSHINT // op s_addr query_id _27=4294967294 + 0 PUSHINT // op s_addr query_id _27=4294967294 _28=0 + s3 s4 XCHG + s1 s3 XCHG + 64 PUSHINT // s_addr _27=4294967294 query_id op _28=0 _29=64 + send_message_back CALLDICT + }> // op s_addr query_id ds elect credits cs + s6 POP // cs s_addr query_id ds elect credits + s0 s5 XCHG // credits s_addr query_id ds elect cs + LDGRAMS // credits s_addr query_id ds elect amount cs + ENDS + NEWC // credits s_addr query_id ds elect amount _35 + s1 s2 XCHG // credits s_addr query_id ds amount elect _35 + STDICT // credits s_addr query_id ds amount _36 + s1 s5 XCHG // amount s_addr query_id ds credits _36 + STDICT // amount s_addr query_id ds _37 + SWAP // amount s_addr query_id _37 ds + STSLICER // amount s_addr query_id _38 + ENDC // amount s_addr query_id _39 + c4 POP + 4184830756 PUSHINT // amount s_addr query_id _41=4184830756 + 0 PUSHINT // amount s_addr query_id _41=4184830756 _42=0 + 24 PUSHINT // amount s_addr query_id _41=4184830756 _42=0 _43=24 + NEWC // amount s_addr query_id _41=4184830756 _42=0 _43=24 _44 + 6 STU // amount s_addr query_id _41=4184830756 _42=0 _46 + s0 s4 XCHG2 // amount _42=0 query_id _41=4184830756 _46 s_addr + STSLICER // amount _42=0 query_id _41=4184830756 _47 + s0 s4 XCHG2 // _41=4184830756 _42=0 query_id _47 amount + STGRAMS // _41=4184830756 _42=0 query_id _48 + s1 s2 XCHG // _41=4184830756 query_id _42=0 _48 + 107 STU // _41=4184830756 query_id _62 + s1 s2 XCHG // query_id _41=4184830756 _62 + 32 STU // query_id _64 + 64 STU // _66 + ENDC // _67 + 64 PUSHINT // _67 _68=64 + SENDRAWMSG + }> + after_code_upgrade PROC:<{ + // s_addr cs query_id + NIP // s_addr query_id + 1313042276 PUSHINT // s_addr query_id op=1313042276 + 3460525924 PUSHINT // s_addr query_id op=1313042276 _5=3460525924 + 0 PUSHINT // s_addr query_id op=1313042276 _5=3460525924 _6=0 + s3 s3 s0 XCHG3 + 64 PUSHINT // s_addr _5=3460525924 query_id op=1313042276 _6=0 _7=64 + send_message_back CALLDICT + }> + upgrade_code PROC:<{ + // s_addr cs query_id + 0 PUSHINT // s_addr cs query_id _4=0 + CONFIGOPTPARAM // s_addr cs query_id c_addr + DUP // s_addr cs query_id c_addr c_addr + ISNULL // s_addr cs query_id c_addr _6 + IFJMP:<{ // s_addr cs query_id c_addr + 4 BLKDROP // + FALSE // _7 + }> // s_addr cs query_id c_addr + CTOS // s_addr cs query_id _9 + 256 PLDU // s_addr cs query_id config_addr + s3 PUSH // s_addr cs query_id config_addr s_addr + REWRITESTDADDR // s_addr cs query_id config_addr src_wc src_addr + SWAP // s_addr cs query_id config_addr src_addr src_wc + INC // s_addr cs query_id config_addr src_addr _16 + s0 s2 XCHG // s_addr cs query_id _16 src_addr config_addr + NEQ // s_addr cs query_id _16 _17 + OR // s_addr cs query_id _18 + IFJMP:<{ // s_addr cs query_id + 3 BLKDROP // + FALSE // _19 + }> // s_addr cs query_id + ACCEPT + SWAP // s_addr query_id cs + LDREF // s_addr query_id code cs + OVER // s_addr query_id code cs code + SETCODE + DUP // s_addr query_id code cs cs + SEMPTY // s_addr query_id code cs _25 + IFNOT:<{ // s_addr query_id code cs + SWAP // s_addr query_id cs code + c3 POP + SWAP // s_addr cs query_id + after_code_upgrade CALLDICT + 0 THROW + }>ELSE<{ + 4 BLKDROP // + }> + TRUE // _30 + }> + recv_internal PROC:<{ + // msg_value in_msg_cell in_msg + SWAP // msg_value in_msg in_msg_cell + CTOS // msg_value in_msg cs + 4 LDU // msg_value in_msg flags cs + SWAP + 1 PUSHINT // msg_value in_msg cs flags _9=1 + AND // msg_value in_msg cs _10 + IFJMP:<{ // msg_value in_msg cs + 3 BLKDROP // + }> // msg_value in_msg cs + LDMSGADDR // msg_value in_msg _61 _60 + DROP // msg_value in_msg s_addr + OVER // msg_value in_msg s_addr in_msg + SEMPTY // msg_value in_msg s_addr _14 + IFJMP:<{ // msg_value in_msg s_addr + NIP // msg_value s_addr + SWAP // s_addr msg_value + process_simple_transfer CALLDICT + }> // msg_value in_msg s_addr + SWAP // msg_value s_addr in_msg + 32 LDU // msg_value s_addr op in_msg + OVER // msg_value s_addr op in_msg op + 0 EQINT // msg_value s_addr op in_msg _21 + IFJMP:<{ // msg_value s_addr op in_msg + 2DROP // msg_value s_addr + SWAP // s_addr msg_value + process_simple_transfer CALLDICT + }> // msg_value s_addr op in_msg + 64 LDU // msg_value s_addr op query_id in_msg + s2 PUSH + 1316189259 PUSHINT // msg_value s_addr op query_id in_msg op _27=1316189259 + EQUAL // msg_value s_addr op query_id in_msg _28 + IFJMP:<{ // msg_value s_addr op query_id in_msg + s2 POP // msg_value s_addr in_msg query_id + s2 s3 XCHG // s_addr msg_value in_msg query_id + process_new_stake CALLDICT + }> // msg_value s_addr op query_id in_msg + s4 POP // in_msg s_addr op query_id + OVER + 1197831204 PUSHINT // in_msg s_addr op query_id op _30=1197831204 + EQUAL // in_msg s_addr op query_id _31 + IFJMP:<{ // in_msg s_addr op query_id + s1 s3 XCHG // op s_addr in_msg query_id + recover_stake CALLDICT + }> // in_msg s_addr op query_id + OVER + 1313042276 PUSHINT // in_msg s_addr op query_id op _33=1313042276 + EQUAL // in_msg s_addr op query_id _34 + IFJMP:<{ // in_msg s_addr op query_id + s2 s3 s3 PUXCPU // query_id s_addr op s_addr in_msg query_id + upgrade_code CALLDICT // query_id s_addr op ok + IF:<{ // query_id s_addr op + 3460525924 PUSHINT // query_id s_addr op _37=3460525924 + }>ELSE<{ // query_id s_addr op + 32 PUSHPOW2DEC // query_id s_addr op _37=4294967295 + }> + 0 PUSHINT // query_id s_addr op _37 _40=0 + s3 s4 XCHG + s3 s3 s0 XCHG3 + 64 PUSHINT // s_addr _37 query_id op _40=0 _41=64 + send_message_back CALLDICT + }> // in_msg s_addr op query_id + OVER + 4000730955 PUSHINT // in_msg s_addr op query_id op _44=4000730955 + EQUAL // in_msg s_addr op query_id cfg_ok + s2 PUSH + 4000730991 PUSHINT // in_msg s_addr op query_id cfg_ok op _46=4000730991 + EQUAL // in_msg s_addr op query_id cfg_ok _47 + s1 s(-1) PUXC // in_msg s_addr op query_id cfg_ok cfg_ok _47 + OR // in_msg s_addr op query_id cfg_ok _48 + IFJMP:<{ // in_msg s_addr op query_id cfg_ok + s2 POP // in_msg s_addr cfg_ok query_id + s2 s3 XCHG + SWAP // s_addr in_msg query_id cfg_ok + config_set_confirmed CALLDICT + }> // in_msg s_addr op query_id cfg_ok + DROP + s3 POP // query_id s_addr op + DUP + 31 PUSHPOW2 // query_id s_addr op op _52 + AND // query_id s_addr op _53 + IFNOTJMP:<{ // query_id s_addr op + 32 PUSHPOW2DEC // query_id s_addr op _54=4294967295 + 0 PUSHINT // query_id s_addr op _54=4294967295 _55=0 + s3 s4 XCHG + s3 s3 s0 XCHG3 + 64 PUSHINT // s_addr _54=4294967295 query_id op _55=0 _56=64 + send_message_back CALLDICT + }> // query_id s_addr op + 3 BLKDROP // + }> + postpone_elections PROC:<{ + // + FALSE // _0 + }> + compute_total_stake PROC:<{ + // l n m_stake + 0 PUSHINT // l n m_stake tot_stake=0 + s0 s2 XCHG // l tot_stake=0 m_stake n + REPEAT:<{ // l tot_stake m_stake + s0 s2 XCHG // m_stake tot_stake l + UNCONS // m_stake tot_stake h l + OVER // m_stake tot_stake h l h + 0 INDEX // m_stake tot_stake h l stake + s0 s2 XCHG // m_stake tot_stake stake l h + 1 INDEX // m_stake tot_stake stake l max_f + s4 PUSH // m_stake tot_stake stake l max_f m_stake + MUL // m_stake tot_stake stake l _13 + 16 RSHIFT# // m_stake tot_stake stake l _15 + s1 s2 XCHG // m_stake tot_stake l stake _15 + MIN // m_stake tot_stake l stake + s1 s2 XCHG // m_stake l tot_stake stake + ADD // m_stake l tot_stake + ROT // l tot_stake m_stake + }> + DROP + NIP // tot_stake + }> + try_elect PROC:<{ + // credits members min_stake max_stake min_total_stake max_stake_factor + 16 PUSHINT // credits members min_stake max_stake min_total_stake max_stake_factor _7=16 + CONFIGOPTPARAM // credits members min_stake max_stake min_total_stake max_stake_factor _8 + CTOS // credits members min_stake max_stake min_total_stake max_stake_factor cs + 16 LDU // credits members min_stake max_stake min_total_stake max_stake_factor _13 cs + 16 LDU // credits members min_stake max_stake min_total_stake max_stake_factor _13 _253 _252 + NIP // credits members min_stake max_stake min_total_stake max_stake_factor _13 cs + 16 LDU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators cs + ENDS + 1 PUSHINT // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators _23=1 + MAX // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators + 0 PUSHINT // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n=0 + NEWDICT // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n=0 sdict + -1 PUSHINT // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n=0 sdict pubkey=-1 + UNTIL:<{ + s9 PUSH + 8 PUSHPOW2 // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict pubkey members _33=256 + DICTUGETNEXT + NULLSWAPIFNOT + NULLSWAPIFNOT // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict cs pubkey f + DUP // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict cs pubkey f f + IF:<{ // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict cs pubkey f + s0 s2 XCHG // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey cs + LDGRAMS // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey _40 cs + 32 LDU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey _40 _42 cs + 32 LDU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey _40 _42 _45 cs + 256 LDU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey _40 _42 _45 _48 cs + 256 LDU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey stake time max_factor addr adnl_addr cs + ENDS + s0 s3 XCHG // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey stake adnl_addr max_factor addr time + NEGATE // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey stake adnl_addr max_factor addr _56 + NEWC // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey stake adnl_addr max_factor addr _56 _57 + s1 s5 XCHG // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey _56 adnl_addr max_factor addr stake _57 + 128 STU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey _56 adnl_addr max_factor addr _59 + s1 s4 XCHG // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr max_factor _56 _59 + 32 STI // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr max_factor _61 + s4 s(-1) PUXC // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr max_factor pubkey _61 + 256 STU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr max_factor _63 + ENDC // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr max_factor _64 + CTOS // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr max_factor key + s1 s10 XCPU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr key max_factor max_stake_factor + MIN // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr key _67 + NEWC // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr key _67 _68 + 32 STU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey addr adnl_addr key _70 + s1 s3 XCHG // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey key adnl_addr addr _70 + 256 STU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey key adnl_addr _72 + 256 STU // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict f pubkey key _74 + s0 s1 s4 XCHG3 + 416 PUSHINT // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n pubkey f _74 key sdict _79 + DICTSETB // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n pubkey f sdict + s0 s3 XCHG // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators sdict pubkey f n + INC // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators sdict pubkey f n + }>ELSE<{ + s3 s4 XCHG + 2SWAP + DROP // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators sdict pubkey f n + }> + SWAP // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators sdict pubkey n f + NOT // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators sdict pubkey n _83 + s3 s3 s0 XCHG3 // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict pubkey _83 + }> // credits members min_stake max_stake min_total_stake max_stake_factor max_validators min_validators n sdict pubkey + DROP + s4 POP // credits members min_stake max_stake min_total_stake sdict max_validators min_validators n + ROT // credits members min_stake max_stake min_total_stake sdict min_validators n max_validators + MIN // credits members min_stake max_stake min_total_stake sdict min_validators n + s0 s1 PUSH2 // credits members min_stake max_stake min_total_stake sdict min_validators n n min_validators + LESS // credits members min_stake max_stake min_total_stake sdict min_validators n _85 + IFJMP:<{ // credits members min_stake max_stake min_total_stake sdict min_validators n + 7 BLKDROP // credits + NEWDICT // credits _86 + NEWDICT // credits _86 _87 + 0 PUSHINT // credits _86 _87 _88=0 + DUP // credits _86 _87 _88=0 _89=0 + }> // credits members min_stake max_stake min_total_stake sdict min_validators n + PUSHNULL // credits members min_stake max_stake min_total_stake sdict min_validators n l + UNTIL:<{ + s0 s3 XCHG + 416 PUSHINT // credits members min_stake max_stake min_total_stake l min_validators n sdict _100 + DICTREMMIN + NULLSWAPIFNOT + NULLSWAPIFNOT // credits members min_stake max_stake min_total_stake l min_validators n sdict cs key f + DUP // credits members min_stake max_stake min_total_stake l min_validators n sdict cs key f f + IF:<{ // credits members min_stake max_stake min_total_stake l min_validators n sdict cs key f + SWAP // credits members min_stake max_stake min_total_stake l min_validators n sdict cs f key + 128 LDU // credits members min_stake max_stake min_total_stake l min_validators n sdict cs f _105 key + s1 s9 XCPU // credits members min_stake max_stake min_total_stake l min_validators n sdict cs f key _105 max_stake + MIN // credits members min_stake max_stake min_total_stake l min_validators n sdict cs f key _108 + SWAP // credits members min_stake max_stake min_total_stake l min_validators n sdict cs f _108 key + 32 LDU // credits members min_stake max_stake min_total_stake l min_validators n sdict cs f _108 _279 _278 + NIP // credits members min_stake max_stake min_total_stake l min_validators n sdict cs f _108 key + 256 PLDU // credits members min_stake max_stake min_total_stake l min_validators n sdict cs f stake pubkey + s0 s3 XCHG // credits members min_stake max_stake min_total_stake l min_validators n sdict pubkey f stake cs + 32 LDU // credits members min_stake max_stake min_total_stake l min_validators n sdict pubkey f stake _117 cs + 256 LDU // credits members min_stake max_stake min_total_stake l min_validators n sdict pubkey f stake _117 _283 _282 + NIP // credits members min_stake max_stake min_total_stake l min_validators n sdict pubkey f stake _117 cs + 256 PLDU // credits members min_stake max_stake min_total_stake l min_validators n sdict pubkey f stake max_f adnl_addr + s1 s3 s0 XCHG3 + s1 s4 XCHG // credits members min_stake max_stake min_total_stake l min_validators n sdict f stake max_f pubkey adnl_addr + 4 TUPLE // credits members min_stake max_stake min_total_stake l min_validators n sdict f _125 + s0 s5 XCHG2 // credits members min_stake max_stake min_total_stake f min_validators n sdict _125 l + CONS // credits members min_stake max_stake min_total_stake f min_validators n sdict l + }>ELSE<{ + s6 s1 s6 XCHG3 + 2DROP // credits members min_stake max_stake min_total_stake f min_validators n sdict l + }> + s0 s4 XCHG // credits members min_stake max_stake min_total_stake l min_validators n sdict f + NOT // credits members min_stake max_stake min_total_stake l min_validators n sdict _127 + s1 s4 XCHG // credits members min_stake max_stake min_total_stake sdict min_validators n l _127 + }> // credits members min_stake max_stake min_total_stake sdict min_validators n l + s3 POP + s4 POP // credits members min_stake n min_total_stake l min_validators + DEC // credits members min_stake n min_total_stake l i + 2DUP // credits members min_stake n min_total_stake l i l1 i + REPEAT:<{ // credits members min_stake n min_total_stake l i l1 + CDR // credits members min_stake n min_total_stake l i l1 + }> + 0 PUSHINT // credits members min_stake n min_total_stake l i l1 _135=0 + DUP // credits members min_stake n min_total_stake l i l1 best_stake=0 m=0 + UNTIL:<{ + s0 s2 XCHG // credits members min_stake n min_total_stake l i m best_stake l1 + UNCONS // credits members min_stake n min_total_stake l i m best_stake _138 l1 + SWAP // credits members min_stake n min_total_stake l i m best_stake l1 _138 + 0 INDEX // credits members min_stake n min_total_stake l i m best_stake l1 stake + s0 s4 XCHG // credits members min_stake n min_total_stake l stake m best_stake l1 i + INC // credits members min_stake n min_total_stake l stake m best_stake l1 i + s4 s8 PUSH2 // credits members min_stake n min_total_stake l stake m best_stake l1 i stake min_stake + GEQ // credits members min_stake n min_total_stake l stake m best_stake l1 i _144 + IF:<{ // credits members min_stake n min_total_stake l stake m best_stake l1 i + s5 s(-1) s4 PU2XC // credits members min_stake n min_total_stake l i m best_stake l1 l i stake + compute_total_stake CALLDICT // credits members min_stake n min_total_stake l i m best_stake l1 tot_stake + s0 s2 PUSH2 // credits members min_stake n min_total_stake l i m best_stake l1 tot_stake tot_stake best_stake + GREATER // credits members min_stake n min_total_stake l i m best_stake l1 tot_stake _147 + IF:<{ // credits members min_stake n min_total_stake l i m best_stake l1 tot_stake + s2 POP + s2 POP // credits members min_stake n min_total_stake l i l1 tot_stake + s2 PUSH // credits members min_stake n min_total_stake l i l1 best_stake m + }>ELSE<{ + s1 s3 XCHG + DROP // credits members min_stake n min_total_stake l i l1 best_stake m + }> + }>ELSE<{ + s3 s4 XCHG2 + DROP // credits members min_stake n min_total_stake l i l1 best_stake m + }> + s3 s6 PUSH2 // credits members min_stake n min_total_stake l i l1 best_stake m i n + GEQ // credits members min_stake n min_total_stake l i l1 best_stake m _148 + }> // credits members min_stake n min_total_stake l i l1 best_stake m + s2 POP + s2 POP + s4 POP + s4 POP // credits members best_stake m min_total_stake l + s2 PUSH // credits members best_stake m min_total_stake l m + 0 EQINT // credits members best_stake m min_total_stake l _150 + s4 s2 PUXC // credits members best_stake m _150 l best_stake min_total_stake + LESS // credits members best_stake m _150 l _151 + s1 s2 XCHG // credits members best_stake m l _150 _151 + OR // credits members best_stake m l _152 + IFJMP:<{ // credits members best_stake m l + 4 BLKDROP // credits + NEWDICT // credits _153 + NEWDICT // credits _153 _154 + 0 PUSHINT // credits _153 _154 _155=0 + DUP // credits _153 _154 _155=0 _156=0 + }> // credits members best_stake m l + DUP // credits members best_stake m l l1 + s0 DUMP // credits members best_stake m l l1 + s2 PUSH // credits members best_stake m l l1 m + DEC // credits members best_stake m l l1 _161 + REPEAT:<{ // credits members best_stake m l l1 + CDR // credits members best_stake m l l1 + }> + CAR // credits members best_stake m l _164 + 0 INDEX // credits members best_stake m l m_stake + 0 PUSHINT // credits members best_stake m l m_stake i=0 + DUP // credits members best_stake m l m_stake i=0 tot_stake=0 + NEWDICT // credits members best_stake m l m_stake i=0 tot_stake=0 vset + NEWDICT // credits members best_stake m l m_stake i=0 tot_stake=0 vset frozen + UNTIL:<{ + s0 s5 XCHG // credits members best_stake m frozen m_stake i tot_stake vset l + UNCONS // credits members best_stake m frozen m_stake i tot_stake vset _179 l + SWAP // credits members best_stake m frozen m_stake i tot_stake vset l _179 + 4 UNTUPLE // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr + s1 s12 PUSH2 + 8 PUSHPOW2 // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr pubkey members _184=256 + DICTUGET + NULLSWAPIFNOT // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr val f + 61 THROWIFNOT + LDGRAMS // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr _295 _294 + NIP // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr val + 64 LDU // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr _297 _296 + NIP // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr val + 256 PLDU // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr src_addr + s8 s11 PUSH2 // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr src_addr i m + LESS // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr src_addr _198 + IF:<{ // credits members best_stake m frozen m_stake i tot_stake vset l stake max_f pubkey adnl_addr src_addr + s3 s9 XCPU // credits members best_stake m frozen m_stake i tot_stake vset l stake src_addr pubkey adnl_addr max_f m_stake + MUL // credits members best_stake m frozen m_stake i tot_stake vset l stake src_addr pubkey adnl_addr _200 + 16 RSHIFT# // credits members best_stake m frozen m_stake i tot_stake vset l stake src_addr pubkey adnl_addr _202 + s4 s(-1) PUXC // credits members best_stake m frozen m_stake i tot_stake vset l stake src_addr pubkey adnl_addr stake _202 + MIN // credits members best_stake m frozen m_stake i tot_stake vset l stake src_addr pubkey adnl_addr true_stake + s4 s4 XCPU // credits members best_stake m frozen m_stake i tot_stake vset l true_stake src_addr pubkey adnl_addr stake true_stake + SUB // credits members best_stake m frozen m_stake i tot_stake vset l true_stake src_addr pubkey adnl_addr stake + s4 PUSH // credits members best_stake m frozen m_stake i tot_stake vset l true_stake src_addr pubkey adnl_addr stake true_stake + 60 LSHIFT# // credits members best_stake m frozen m_stake i tot_stake vset l true_stake src_addr pubkey adnl_addr stake _207 + s13 PUSH // credits members best_stake m frozen m_stake i tot_stake vset l true_stake src_addr pubkey adnl_addr stake _207 best_stake + DIV // credits members best_stake m frozen m_stake i tot_stake vset l true_stake src_addr pubkey adnl_addr stake weight + s8 s5 XCPU // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake true_stake + ADD // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake + 2390828938 PUSHINT // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _211=2390828938 + s3 PUSH // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _211=2390828938 adnl_addr + IF:<{ // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _211=2390828938 + 115 PUSHINT // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _211=2390828938 _212=115 + }>ELSE<{ // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _211=2390828938 + 83 PUSHINT // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _211=2390828938 _212=83 + }> + NEWC // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _211=2390828938 _212 _215 + 8 STU // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _211=2390828938 _217 + 32 STU // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _219 + s4 s(-1) PUXC // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake pubkey _219 + 256 STU // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake _221 + s9 s(-1) PUXC // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake weight _221 + 64 STU // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake vinfo + s3 PUSH // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake vinfo adnl_addr + IF:<{ // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey adnl_addr stake tot_stake vinfo + s1 s3 XCHG // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey tot_stake stake adnl_addr vinfo + 256 STU // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey tot_stake stake vinfo + }>ELSE<{ + s0 s3 XCHG2 + DROP // credits members best_stake m frozen m_stake i weight vset l true_stake src_addr pubkey tot_stake stake vinfo + }> + SWAP + 16 PUSHINT + s10 s8 s8 PUXC2 // credits members best_stake m frozen m_stake i weight stake l true_stake src_addr pubkey tot_stake vinfo i vset _228=16 + DICTUSETB // credits members best_stake m frozen m_stake i weight stake l true_stake src_addr pubkey tot_stake vset + FALSE // credits members best_stake m frozen m_stake i weight stake l true_stake src_addr pubkey tot_stake vset _231 + s4 PUSH + NEWC // credits members best_stake m frozen m_stake i weight stake l true_stake src_addr pubkey tot_stake vset _231 src_addr _232 + 256 STU // credits members best_stake m frozen m_stake i weight stake l true_stake src_addr pubkey tot_stake vset _231 _234 + s1 s9 XCHG // credits members best_stake m frozen m_stake i _231 stake l true_stake src_addr pubkey tot_stake vset weight _234 + 64 STU // credits members best_stake m frozen m_stake i _231 stake l true_stake src_addr pubkey tot_stake vset _236 + s0 s5 XCHG2 // credits members best_stake m frozen m_stake i _231 stake l vset src_addr pubkey tot_stake _236 true_stake + STGRAMS // credits members best_stake m frozen m_stake i _231 stake l vset src_addr pubkey tot_stake _237 + s1 s7 XCHG // credits members best_stake m frozen m_stake i tot_stake stake l vset src_addr pubkey _231 _237 + 1 STI // credits members best_stake m frozen m_stake i tot_stake stake l vset src_addr pubkey _239 + s0 s1 s9 XCHG3 + 8 PUSHPOW2 // credits members best_stake m src_addr m_stake i tot_stake stake l vset _239 pubkey frozen _240=256 + DICTUSETB // credits members best_stake m src_addr m_stake i tot_stake stake l vset frozen + }>ELSE<{ + s0 s10 XCHG + s4 s6 XCHG + s0 s3 XCHG + 3 BLKDROP // credits members best_stake m src_addr m_stake i tot_stake stake l vset frozen + }> + s3 PUSH // credits members best_stake m src_addr m_stake i tot_stake stake l vset frozen stake + IF:<{ // credits members best_stake m src_addr m_stake i tot_stake stake l vset frozen + s11 s7 s3 XCHG3 // l members best_stake m vset m_stake i tot_stake frozen credits src_addr stake + ~credit_to CALLDICT // l members best_stake m vset m_stake i tot_stake frozen credits + }>ELSE<{ + s11 s7 s3 XCHG3 + 2DROP // l members best_stake m vset m_stake i tot_stake frozen credits + }> + s0 s3 XCHG // l members best_stake m vset m_stake credits tot_stake frozen i + INC // l members best_stake m vset m_stake credits tot_stake frozen i + s9 PUSH // l members best_stake m vset m_stake credits tot_stake frozen i l + ISNULL // l members best_stake m vset m_stake credits tot_stake frozen i _246 + s4 s10 XCHG + s4 s6 XCHG + s4 s4 s0 XCHG3 // credits members best_stake m l m_stake i tot_stake vset frozen _246 + }> // credits members best_stake m l m_stake i tot_stake vset frozen + s3 POP + s3 POP + s3 POP + s5 POP // credits frozen best_stake m tot_stake vset + s1 s3 PUXC // credits frozen vset m tot_stake tot_stake best_stake + EQUAL // credits frozen vset m tot_stake _248 + 49 THROWIFNOT + s2 s3 XCHG + SWAP // credits vset frozen tot_stake m + }> + conduct_elections PROC:<{ + // ds elect credits + SWAP // ds credits elect + unpack_elect CALLDICT // ds credits _130 _131 _132 _133 _134 _135 _136 + s4 POP // ds credits elect_at elect_close finished total_stake members failed + NOW // ds credits elect_at elect_close finished total_stake members failed _11 + s5 PUSH // ds credits elect_at elect_close finished total_stake members failed _11 elect_close + LESS // ds credits elect_at elect_close finished total_stake members failed _12 + IFJMP:<{ // ds credits elect_at elect_close finished total_stake members failed + 8 BLKDROP // + FALSE // _13 + }> // ds credits elect_at elect_close finished total_stake members failed + 0 PUSHINT // ds credits elect_at elect_close finished total_stake members failed _14=0 + CONFIGOPTPARAM // ds credits elect_at elect_close finished total_stake members failed _15 + ISNULL // ds credits elect_at elect_close finished total_stake members failed _16 + IFJMP:<{ // ds credits elect_at elect_close finished total_stake members failed + 8 BLKDROP // + postpone_elections CALLDICT // _17 + }> // ds credits elect_at elect_close finished total_stake members failed + 17 PUSHINT // ds credits elect_at elect_close finished total_stake members failed _19=17 + CONFIGOPTPARAM // ds credits elect_at elect_close finished total_stake members failed _20 + CTOS // ds credits elect_at elect_close finished total_stake members failed cs + LDGRAMS // ds credits elect_at elect_close finished total_stake members failed min_stake cs + LDGRAMS // ds credits elect_at elect_close finished total_stake members failed min_stake max_stake cs + LDGRAMS // ds credits elect_at elect_close finished total_stake members failed min_stake max_stake min_total_stake cs + 32 LDU // ds credits elect_at elect_close finished total_stake members failed min_stake max_stake min_total_stake max_stake_factor cs + ENDS + s6 s1 PUSH2 // ds credits elect_at elect_close finished total_stake members failed min_stake max_stake min_total_stake max_stake_factor total_stake min_total_stake + LESS // ds credits elect_at elect_close finished total_stake members failed min_stake max_stake min_total_stake max_stake_factor _35 + IFJMP:<{ // ds credits elect_at elect_close finished total_stake members failed min_stake max_stake min_total_stake max_stake_factor + 12 BLKDROP // + postpone_elections CALLDICT // _36 + }> // ds credits elect_at elect_close finished total_stake members failed min_stake max_stake min_total_stake max_stake_factor + s0 s4 XCHG // ds credits elect_at elect_close finished total_stake members max_stake_factor min_stake max_stake min_total_stake failed + IFJMP:<{ // ds credits elect_at elect_close finished total_stake members max_stake_factor min_stake max_stake min_total_stake + 11 BLKDROP // + postpone_elections CALLDICT // _37 + }> // ds credits elect_at elect_close finished total_stake members max_stake_factor min_stake max_stake min_total_stake + s0 s6 XCHG // ds credits elect_at elect_close min_total_stake total_stake members max_stake_factor min_stake max_stake finished + IFJMP:<{ // ds credits elect_at elect_close min_total_stake total_stake members max_stake_factor min_stake max_stake + 10 BLKDROP // + FALSE // _38 + }> // ds credits elect_at elect_close min_total_stake total_stake members max_stake_factor min_stake max_stake + s3 s8 XCHG + s8 PUSH + s3 s2 XCPU + s7 s7 XCHG2 // ds members elect_at elect_close min_stake total_stake credits members min_stake max_stake min_total_stake max_stake_factor + try_elect CALLDICT // ds members elect_at elect_close min_stake total_stake credits vdict frozen total_stakes cnt + DUP // ds members elect_at elect_close min_stake total_stake credits vdict frozen total_stakes cnt cnt + 0 EQINT // ds members elect_at elect_close min_stake total_stake credits vdict frozen total_stakes cnt failed + DUP // ds members elect_at elect_close min_stake total_stake credits vdict frozen total_stakes cnt failed failed + NOT // ds members elect_at elect_close min_stake total_stake credits vdict frozen total_stakes cnt failed finished + s10 PUSH + s0 s6 XCHG + s5 s10 XCHG + s4 s9 XCHG + s3 s8 XCHG + s12 s12 s12 XCHG3 // ds vdict elect_at frozen total_stakes cnt credits elect_at elect_close min_stake total_stake members failed finished + pack_elect CALLDICT // ds vdict elect_at frozen total_stakes cnt credits elect + s2 PUSH // ds vdict elect_at frozen total_stakes cnt credits elect cnt + IFNOTJMP:<{ // ds vdict elect_at frozen total_stakes cnt credits elect + s2 POP + s2 POP + s2 POP + s2 POP + s2 POP // ds elect credits + NEWC // ds elect credits _48 + s1 s2 XCHG // ds credits elect _48 + STDICT // ds credits _49 + STDICT // ds _50 + SWAP // _50 ds + STSLICER // _51 + ENDC // _52 + c4 POP + postpone_elections CALLDICT // _54 + }> // ds vdict elect_at frozen total_stakes cnt credits elect + get_validator_conf CALLDICT // ds vdict elect_at frozen total_stakes cnt credits elect _150 _151 _152 _153 + s2 POP // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held elect_end_before + NOW // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held elect_end_before _61 + SWAP // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held _61 elect_end_before + ADD // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held _62 + -60 ADDCONST // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held _64 + s8 PUSH // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held _64 elect_at + MAX // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start + 16 PUSHINT // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _67=16 + CONFIGOPTPARAM // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _68 + CTOS // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _69 + 16 PUSHINT // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _69 _70=16 + SDSKIPFIRST // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _71 + 16 PLDU // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start main_validators + s6 s(-1) PUXC // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start cnt main_validators + MIN // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _75 + s1 s3 PUSH2 // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _75 start elect_for + ADD // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _75 _76 + 17 PUSHINT // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _75 _76 _77=17 + NEWC // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _75 _76 _77=17 _78 + 8 STU // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _75 _76 _80 + s3 s(-1) PUXC // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _75 _76 start _80 + 32 STU // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _75 _76 _82 + 32 STU // ds vdict elect_at frozen total_stakes cnt credits elect elect_for stake_held start _75 _84 + s1 s7 XCHG // ds vdict elect_at frozen total_stakes _75 credits elect elect_for stake_held start cnt _84 + 16 STU // ds vdict elect_at frozen total_stakes _75 credits elect elect_for stake_held start _86 + s1 s6 XCHG // ds vdict elect_at frozen total_stakes start credits elect elect_for stake_held _75 _86 + 16 STU // ds vdict elect_at frozen total_stakes start credits elect elect_for stake_held _88 + s0 s9 XCHG // ds _88 elect_at frozen total_stakes start credits elect elect_for stake_held vdict + CTOS // ds _88 elect_at frozen total_stakes start credits elect elect_for stake_held _89 + s1 s9 XCHG // ds stake_held elect_at frozen total_stakes start credits elect elect_for _88 _89 + STSLICER // ds stake_held elect_at frozen total_stakes start credits elect elect_for _90 + ENDC // ds stake_held elect_at frozen total_stakes start credits elect elect_for vset + 0 PUSHINT // ds stake_held elect_at frozen total_stakes start credits elect elect_for vset _93=0 + CONFIGOPTPARAM // ds stake_held elect_at frozen total_stakes start credits elect elect_for vset _94 + CTOS // ds stake_held elect_at frozen total_stakes start credits elect elect_for vset _95 + 256 PLDU // ds stake_held elect_at frozen total_stakes start credits elect elect_for vset config_addr + s1 s8 PUSH2 // ds stake_held elect_at frozen total_stakes start credits elect elect_for vset config_addr vset elect_at + send_validator_set_to_config CALLDICT + s0 s9 XCHG // vset stake_held elect_at frozen total_stakes start credits elect elect_for ds + LDDICT // vset stake_held elect_at frozen total_stakes start credits elect elect_for past_elect ds + FALSE // vset stake_held elect_at frozen total_stakes start credits elect elect_for past_elect ds _103 + s0 s11 XCHG // _103 stake_held elect_at frozen total_stakes start credits elect elect_for past_elect ds vset + HASHCU // _103 stake_held elect_at frozen total_stakes start credits elect elect_for past_elect ds _104 + s6 s3 XCHG2 // _103 stake_held elect_at frozen total_stakes ds credits elect _104 past_elect start elect_for + ADD // _103 stake_held elect_at frozen total_stakes ds credits elect _104 past_elect _105 + s9 PUSH // _103 stake_held elect_at frozen total_stakes ds credits elect _104 past_elect _105 stake_held + ADD // _103 stake_held elect_at frozen total_stakes ds credits elect _104 past_elect _106 + NEWC // _103 stake_held elect_at frozen total_stakes ds credits elect _104 past_elect _106 _107 + 32 STU // _103 stake_held elect_at frozen total_stakes ds credits elect _104 past_elect _109 + s1 s9 XCHG // _103 past_elect elect_at frozen total_stakes ds credits elect _104 stake_held _109 + 32 STU // _103 past_elect elect_at frozen total_stakes ds credits elect _104 _111 + 256 STU // _103 past_elect elect_at frozen total_stakes ds credits elect _113 + s1 s5 XCHG // _103 past_elect elect_at elect total_stakes ds credits frozen _113 + STDICT // _103 past_elect elect_at elect total_stakes ds credits _114 + s0 s3 XCHG2 // _103 past_elect elect_at elect credits ds _114 total_stakes + STGRAMS // _103 past_elect elect_at elect credits ds _115 + 0 PUSHINT // _103 past_elect elect_at elect credits ds _115 _116=0 + STGRAMS // _103 past_elect elect_at elect credits ds _117 + s1 s6 XCHG // ds past_elect elect_at elect credits _103 _117 + 1 STI // ds past_elect elect_at elect credits _119 + s0 s3 s4 XCHG3 + 32 PUSHINT // ds elect credits _119 elect_at past_elect _120=32 + DICTUSETB // ds elect credits past_elect + NEWC // ds elect credits past_elect _122 + s1 s3 XCHG // ds past_elect credits elect _122 + STDICT // ds past_elect credits _123 + STDICT // ds past_elect _124 + STDICT // ds _125 + SWAP // _125 ds + STSLICER // _126 + ENDC // _127 + c4 POP + TRUE // _129 + }> + update_active_vset_id PROC:<{ + // + load_data CALLDICT // elect credits past_elect grams active_id active_hash + 34 PUSHINT // elect credits past_elect grams active_id active_hash _8=34 + CONFIGOPTPARAM // elect credits past_elect grams active_id active_hash _9 + HASHCU // elect credits past_elect grams active_id active_hash cur_hash + s0 s1 PUSH2 // elect credits past_elect grams active_id active_hash cur_hash cur_hash active_hash + EQUAL // elect credits past_elect grams active_id active_hash cur_hash _11 + IFJMP:<{ // elect credits past_elect grams active_id active_hash cur_hash + 7 BLKDROP // + FALSE // _12 + }> // elect credits past_elect grams active_id active_hash cur_hash + s2 PUSH // elect credits past_elect grams active_id active_hash cur_hash active_id + IF:<{ // elect credits past_elect grams active_id active_hash cur_hash + s2 s4 PUSH2 + 32 PUSHINT // elect credits past_elect grams active_id active_hash cur_hash active_id past_elect _15=32 + DICTUGET + NULLSWAPIFNOT // elect credits past_elect grams active_id active_hash cur_hash fs f + IF:<{ // elect credits past_elect grams active_id active_hash cur_hash fs + 32 LDU // elect credits past_elect grams active_id active_hash cur_hash _99 _98 + NIP // elect credits past_elect grams active_id active_hash cur_hash fs + DUP // elect credits past_elect grams active_id active_hash cur_hash fs0 fs + 32 LDU // elect credits past_elect grams active_id active_hash cur_hash fs0 _24 fs + 256 LDU // elect credits past_elect grams active_id active_hash cur_hash fs0 _24 _103 _102 + DROP // elect credits past_elect grams active_id active_hash cur_hash fs0 stake_held hash + s0 s4 XCHG2 // elect credits past_elect grams active_id stake_held cur_hash fs0 hash active_hash + EQUAL // elect credits past_elect grams active_id stake_held cur_hash fs0 _31 + 57 THROWIFNOT + NOW // elect credits past_elect grams active_id stake_held cur_hash fs0 _33 + s0 s3 XCHG2 // elect credits past_elect grams active_id fs0 cur_hash _33 stake_held + ADD // elect credits past_elect grams active_id fs0 cur_hash unfreeze_time + NEWC // elect credits past_elect grams active_id fs0 cur_hash unfreeze_time _36 + 32 STU // elect credits past_elect grams active_id fs0 cur_hash _38 + ROT // elect credits past_elect grams active_id cur_hash _38 fs0 + STSLICER // elect credits past_elect grams active_id cur_hash _39 + s0 s0 s4 XCHG3 + 32 PUSHINT // elect credits cur_hash grams _39 active_id past_elect _40=32 + DICTUSETB // elect credits cur_hash grams past_elect + }>ELSE<{ + s1 s5 XCHG + s1 s3 XCHG + 3 BLKDROP // elect credits cur_hash grams past_elect + }> + }>ELSE<{ + s4 s1 s4 XCHG3 + 2DROP // elect credits cur_hash grams past_elect + }> + -1 PUSHINT // elect credits cur_hash grams past_elect id=-1 + UNTIL:<{ + OVER + 32 PUSHINT // elect credits cur_hash grams past_elect id past_elect _46=32 + DICTUGETNEXT + NULLSWAPIFNOT + NULLSWAPIFNOT // elect credits cur_hash grams past_elect fs id f + DUP // elect credits cur_hash grams past_elect fs id f f + IF:<{ // elect credits cur_hash grams past_elect fs id f + s0 s2 XCHG // elect credits cur_hash grams past_elect f id fs + 64 LDU // elect credits cur_hash grams past_elect f id _50 fs + 256 LDU // elect credits cur_hash grams past_elect f id tm hash fs + s1 s7 PUSH2 // elect credits cur_hash grams past_elect f id tm hash fs hash cur_hash + EQUAL // elect credits cur_hash grams past_elect f id tm hash fs _56 + IF:<{ // elect credits cur_hash grams past_elect f id tm hash fs + s4 POP // elect credits cur_hash grams past_elect fs id tm hash + s0 s3 XCHG // elect credits cur_hash grams past_elect hash id tm fs + LDDICT // elect credits cur_hash grams past_elect hash id tm _60 fs + LDGRAMS // elect credits cur_hash grams past_elect hash id tm _60 _62 fs + LDGRAMS // elect credits cur_hash grams past_elect hash id tm dict total_stake bonuses fs + s8 PUSH // elect credits cur_hash grams past_elect hash id tm dict total_stake bonuses fs grams + 3 RSHIFT# // elect credits cur_hash grams past_elect hash id tm dict total_stake bonuses fs amount + s9 s9 XCPU // elect credits cur_hash amount past_elect hash id tm dict total_stake bonuses fs grams amount + SUB // elect credits cur_hash amount past_elect hash id tm dict total_stake bonuses fs grams + s2 s9 XCHG2 // elect credits cur_hash grams past_elect hash id tm dict total_stake fs bonuses amount + ADD // elect credits cur_hash grams past_elect hash id tm dict total_stake fs bonuses + NEWC // elect credits cur_hash grams past_elect hash id tm dict total_stake fs bonuses _72 + s1 s5 XCHG // elect credits cur_hash grams past_elect hash id bonuses dict total_stake fs tm _72 + 64 STU // elect credits cur_hash grams past_elect hash id bonuses dict total_stake fs _74 + s1 s6 XCHG // elect credits cur_hash grams past_elect fs id bonuses dict total_stake hash _74 + 256 STU // elect credits cur_hash grams past_elect fs id bonuses dict total_stake _76 + s1 s2 XCHG // elect credits cur_hash grams past_elect fs id bonuses total_stake dict _76 + STDICT // elect credits cur_hash grams past_elect fs id bonuses total_stake _77 + SWAP // elect credits cur_hash grams past_elect fs id bonuses _77 total_stake + STGRAMS // elect credits cur_hash grams past_elect fs id bonuses _78 + SWAP // elect credits cur_hash grams past_elect fs id _78 bonuses + STGRAMS // elect credits cur_hash grams past_elect fs id _79 + ROT // elect credits cur_hash grams past_elect id _79 fs + STSLICER // elect credits cur_hash grams past_elect id _80 + SWAP + 32 PUSHINT + s1 s3 s3 PUXC2 // elect credits cur_hash grams id _80 id past_elect _81=32 + DICTUSETB // elect credits cur_hash grams id past_elect + FALSE // elect credits cur_hash grams id past_elect f + }>ELSE<{ + s3 s5 XCHG + s3 s4 XCHG + 3 BLKDROP // elect credits cur_hash grams id past_elect f + }> + }>ELSE<{ + s3 s0 s3 XCHG3 + DROP // elect credits cur_hash grams id past_elect f + }> + NOT // elect credits cur_hash grams id past_elect _84 + s1 s2 XCHG // elect credits cur_hash grams past_elect id _84 + }> // elect credits cur_hash grams past_elect id + DUP // elect credits cur_hash grams past_elect id id + ISNULL // elect credits cur_hash grams past_elect id _85 + IF:<{ // elect credits cur_hash grams past_elect id + DROP // elect credits cur_hash grams past_elect + 0 PUSHINT // elect credits cur_hash grams past_elect _86=0 + }>ELSE<{ // elect credits cur_hash grams past_elect _86 + }> // elect credits active_hash grams past_elect active_id + s0 s3 XCHG2 // elect credits past_elect grams active_id active_hash + store_data CALLDICT + TRUE // _89 + }> + cell_hash_eq? PROC:<{ + // vset expected_vset_hash + OVER // vset expected_vset_hash vset + ISNULL // vset expected_vset_hash _2 + IF:<{ // vset expected_vset_hash + 2DROP // + FALSE // _3 + }>ELSE<{ // vset expected_vset_hash + SWAP // expected_vset_hash vset + HASHCU // expected_vset_hash _5 + SWAP // _5 expected_vset_hash + EQUAL // _3 + }> + }> + validator_set_installed PROC:<{ + // ds elect credits + SWAP // ds credits elect + unpack_elect CALLDICT // ds credits _44 _45 _46 _47 _48 _49 _50 + s0 s5 XCHG + 5 BLKDROP // ds credits elect_at finished + IFNOTJMP:<{ // ds credits elect_at + 3 BLKDROP // + FALSE // _11 + }> // ds credits elect_at + s0 s2 XCHG // elect_at credits ds + LDDICT // elect_at credits past_elections ds + s3 s1 XCPU + 32 PUSHINT // ds credits past_elections elect_at past_elections _17=32 + DICTUGET + NULLSWAPIFNOT // ds credits past_elections fs f + IFNOTJMP:<{ // ds credits past_elections fs + 4 BLKDROP // + FALSE // _19 + }> // ds credits past_elections fs + 64 PUSHINT // ds credits past_elections fs _21=64 + SDSKIPFIRST // ds credits past_elections _22 + 256 PLDU // ds credits past_elections vset_hash + 34 PUSHINT // ds credits past_elections vset_hash _25=34 + CONFIGOPTPARAM // ds credits past_elections vset_hash _26 + OVER // ds credits past_elections vset_hash _26 vset_hash + cell_hash_eq? CALLDICT // ds credits past_elections vset_hash _27 + 36 PUSHINT // ds credits past_elections vset_hash _27 _28=36 + CONFIGOPTPARAM // ds credits past_elections vset_hash _27 _29 + ROT // ds credits past_elections _27 _29 vset_hash + cell_hash_eq? CALLDICT // ds credits past_elections _27 _30 + OR // ds credits past_elections _31 + IFJMP:<{ // ds credits past_elections + FALSE // ds credits past_elections _32 + NEWC // ds credits past_elections _32 _33 + 1 STI // ds credits past_elections _35 + s1 s2 XCHG // ds past_elections credits _35 + STDICT // ds past_elections _36 + STDICT // ds _37 + SWAP // _37 ds + STSLICER // _38 + ENDC // _39 + c4 POP + update_active_vset_id CALLDICT // _41 + DROP // + TRUE // _42 + }> // ds credits past_elections + 3 BLKDROP // + FALSE // _43 + }> + check_unfreeze PROC:<{ + // + load_data CALLDICT // elect credits past_elect grams active_id active_hash + -1 PUSHINT // elect credits past_elect grams active_id active_hash id=-1 + UNTIL:<{ + s4 PUSH + 32 PUSHINT // elect credits past_elect grams active_id active_hash id past_elect _11=32 + DICTUGETNEXT + NULLSWAPIFNOT + NULLSWAPIFNOT // elect credits past_elect grams active_id active_hash fs id f + DUP // elect credits past_elect grams active_id active_hash fs id f f + IF:<{ // elect credits past_elect grams active_id active_hash fs id f + s0 s2 XCHG // elect credits past_elect grams active_id active_hash f id fs + 32 LDU // elect credits past_elect grams active_id active_hash f id _39 _38 + DROP // elect credits past_elect grams active_id active_hash f id unfreeze_at + NOW // elect credits past_elect grams active_id active_hash f id unfreeze_at _17 + LEQ // elect credits past_elect grams active_id active_hash f id _18 + s1 s4 PUSH2 // elect credits past_elect grams active_id active_hash f id _18 id active_id + NEQ // elect credits past_elect grams active_id active_hash f id _18 _19 + AND // elect credits past_elect grams active_id active_hash f id _20 + IF:<{ // elect credits past_elect grams active_id active_hash f id + NIP // elect credits past_elect grams active_id active_hash id + s5 s4 s4 XC2PU // elect active_hash id grams active_id credits past_elect id + unfreeze_all CALLDICT // elect active_hash id grams active_id credits past_elect unused_prizes + s1 s4 XCHG // elect active_hash id past_elect active_id credits grams unused_prizes + ADD // elect active_hash id past_elect active_id credits grams + s6 s1 s3 PUSH3 + s3 s5 s8 PUSH3 // elect active_hash id past_elect active_id credits grams elect credits past_elect grams active_id active_hash + store_data CALLDICT + FALSE // elect active_hash id past_elect active_id credits grams f + }>ELSE<{ + s6 s1 s5 XCHG3 + s4 s4 XCHG2 // elect active_hash id past_elect active_id credits grams f + }> + }>ELSE<{ + s3 s7 XCHG + s1 s6 XCHG + s5 s0 s5 XCHG3 + DROP // elect active_hash id past_elect active_id credits grams f + }> + NOT // elect active_hash id past_elect active_id credits grams _26 + s2 s6 XCHG + s4 s5 XCHG + s1 s4 XCHG // elect credits past_elect grams active_id active_hash id _26 + }> // elect credits past_elect grams active_id active_hash id + s0 s6 XCHG + 6 BLKDROP // id + ISNULL // _27 + NOT // _28 + }> + announce_new_elections PROC:<{ + // ds elect credits + NIP // ds credits + 36 PUSHINT // ds credits _4=36 + CONFIGOPTPARAM // ds credits next_vset + ISNULL // ds credits _6 + IFNOTJMP:<{ // ds credits + 2DROP // + FALSE // _7 + }> // ds credits + 1 PUSHINT // ds credits _9=1 + CONFIGOPTPARAM // ds credits _10 + CTOS // ds credits _11 + 256 PLDU // ds credits elector_addr + MYADDR // ds credits elector_addr _16 + REWRITESTDADDR // ds credits elector_addr my_wc my_addr + SWAP // ds credits elector_addr my_addr my_wc + INC // ds credits elector_addr my_addr _19 + s0 s2 XCHG // ds credits _19 my_addr elector_addr + NEQ // ds credits _19 _20 + OR // ds credits _21 + IFJMP:<{ // ds credits + 2DROP // + FALSE // _22 + }> // ds credits + 34 PUSHINT // ds credits _24=34 + CONFIGOPTPARAM // ds credits cur_vset + DUP // ds credits cur_vset cur_vset + ISNULL // ds credits cur_vset _26 + IFJMP:<{ // ds credits cur_vset + 3 BLKDROP // + FALSE // _27 + }> // ds credits cur_vset + get_validator_conf CALLDICT // ds credits cur_vset _76 _77 _78 _79 + DROP + s2 POP // ds credits cur_vset elect_end_before elect_begin_before + s0 s2 XCHG // ds credits elect_begin_before elect_end_before cur_vset + CTOS // ds credits elect_begin_before elect_end_before _34 + 40 PUSHINT // ds credits elect_begin_before elect_end_before _34 _37 + SDSKIPFIRST // ds credits elect_begin_before elect_end_before _38 + 32 PLDU // ds credits elect_begin_before elect_end_before cur_valid_until + NOW // ds credits elect_begin_before elect_end_before cur_valid_until t + s1 s3 XCPU // ds credits elect_begin_before elect_end_before t cur_valid_until elect_begin_before + SUB // ds credits elect_begin_before elect_end_before t t0 + 2DUP // ds credits elect_begin_before elect_end_before t t0 t t0 + LESS // ds credits elect_begin_before elect_end_before t t0 _45 + IFJMP:<{ // ds credits elect_begin_before elect_end_before t t0 + 6 BLKDROP // + FALSE // _46 + }> // ds credits elect_begin_before elect_end_before t t0 + 2DUP // ds credits elect_begin_before elect_end_before t t0 t t0 + SUB // ds credits elect_begin_before elect_end_before t t0 _47 + 60 LESSINT // ds credits elect_begin_before elect_end_before t t0 _49 + IF:<{ // ds credits elect_begin_before elect_end_before t t0 + NIP // ds credits elect_begin_before elect_end_before t + }>ELSE<{ + DROP // ds credits elect_begin_before elect_end_before t + }> + 17 PUSHINT // ds credits elect_begin_before elect_end_before t _52=17 + CONFIGOPTPARAM // ds credits elect_begin_before elect_end_before t _53 + CTOS // ds credits elect_begin_before elect_end_before t _54 + LDGRAMS // ds credits elect_begin_before elect_end_before t _81 _80 + DROP // ds credits elect_begin_before elect_end_before t min_stake + s0 s3 XCHG // ds credits min_stake elect_end_before t elect_begin_before + ADD // ds credits min_stake elect_end_before elect_at + s0 DUMP // ds credits min_stake elect_end_before elect_at + s0 s1 PUXC // ds credits min_stake elect_at elect_at elect_end_before + SUB // ds credits min_stake elect_at elect_close + 0 PUSHINT // ds credits min_stake elect_at elect_close _62=0 + NEWDICT // ds credits min_stake elect_at elect_close _62=0 _63 + FALSE // ds credits min_stake elect_at elect_close _62=0 _63 _64 + s4 s5 XCHG + s3 s4 XCHG + FALSE // ds credits elect_at elect_close min_stake _62=0 _63 _64 _65 + pack_elect CALLDICT // ds credits elect + NEWC // ds credits elect _67 + STDICT // ds credits _68 + STDICT // ds _69 + SWAP // _69 ds + STSLICER // _70 + ENDC // _71 + c4 POP + TRUE // _73 + }> + run_ticktock PROC:<{ + // is_tock + DROP // + c4 PUSH // _2 + CTOS // ds + LDDICT // _6 ds + LDDICT // elect credits ds + s2 PUSH // elect credits ds elect + ISNULL // elect credits ds _10 + IF:<{ // elect credits ds + -ROT // ds elect credits + announce_new_elections CALLDICT // _18 + 0 THROWIF + }>ELSE<{ // elect credits ds + s0 s2 s1 PUSH3 // elect credits ds ds elect credits + conduct_elections CALLDICT // elect credits ds _12 + 0 THROWIF + -ROT // ds elect credits + validator_set_installed CALLDICT // _15 + 0 THROWIF + }> + update_active_vset_id CALLDICT // _21 + 0 THROWIF + check_unfreeze CALLDICT // _23 + DROP // + }> + active_election_id PROC:<{ + // + c4 PUSH // _1 + CTOS // _2 + PLDDICT // elect + DUP // elect elect + ISNULL // elect _4 + IF:<{ // elect + DROP // + 0 PUSHINT // _5=0 + }>ELSE<{ // elect + CTOS // _7 + 32 PLDU // _5 + }> + }> + participates_in PROC:<{ + // validator_pubkey + c4 PUSH // validator_pubkey _2 + CTOS // validator_pubkey _3 + PLDDICT // validator_pubkey elect + DUP // validator_pubkey elect elect + ISNULL // validator_pubkey elect _5 + IFJMP:<{ // validator_pubkey elect + 2DROP // + 0 PUSHINT // _6=0 + }> // validator_pubkey elect + unpack_elect CALLDICT // validator_pubkey _23 _24 _25 _26 _27 _28 _29 + s2 s6 XCHG + 6 BLKDROP // validator_pubkey members + 8 PUSHPOW2 // validator_pubkey members _17=256 + DICTUGET + NULLSWAPIFNOT // mem found + IF:<{ // mem + LDGRAMS // _33 _32 + DROP // _19 + }>ELSE<{ // mem + DROP // + 0 PUSHINT // _19=0 + }> + }> + participant_list PROC:<{ + // + c4 PUSH // _1 + CTOS // _2 + PLDDICT // elect + DUP // elect elect + ISNULL // elect _4 + IFJMP:<{ // elect + DROP // + PUSHNULL // _5 + }> // elect + unpack_elect CALLDICT // _35 _36 _37 _38 _39 _40 _41 + s2 s6 XCHG + 6 BLKDROP // members + PUSHNULL // members l + 256 PUSHPOW2DEC // members l id + UNTIL:<{ + s2 PUSH + 8 PUSHPOW2 // members l id members _28=256 + DICTUGETPREV + NULLSWAPIFNOT + NULLSWAPIFNOT // members l fs id f + DUP // members l fs id f f + IF:<{ // members l fs id f + s0 s2 XCHG // members l f id fs + LDGRAMS // members l f id _46 _45 + DROP // members l f id _30 + s1 s(-1) PUXC // members l f id id _30 + PAIR // members l f id _32 + s0 s3 XCHG2 // members id f _32 l + CONS // members id f l + }>ELSE<{ + 2SWAP + DROP // members id f l + }> + SWAP // members id l f + NOT // members id l _34 + s1 s2 XCHG // members l id _34 + }> // members l id + DROP + NIP // l + }> + compute_returned_stake PROC:<{ + // wallet_addr + c4 PUSH // wallet_addr _2 + CTOS // wallet_addr cs + LDDICT // wallet_addr _19 _18 + NIP // wallet_addr cs + LDDICT // wallet_addr _21 _20 + DROP // wallet_addr credits + 8 PUSHPOW2 // wallet_addr credits _12=256 + DICTUGET + NULLSWAPIFNOT // val f + IF:<{ // val + LDGRAMS // _25 _24 + DROP // _14 + }>ELSE<{ // val + DROP // + 0 PUSHINT // _14=0 + }> + }> +}END>c diff --git a/submodules/ton/tonlib-src/crypto/smartcont/highload-wallet-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/highload-wallet-code.fif new file mode 100644 index 00000000000..d2122a96fbd --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/highload-wallet-code.fif @@ -0,0 +1,79 @@ +// automatically generated from `smartcont/stdlib.fc` `smartcont/highload-wallet-code.fc` +PROGRAM{ + DECLPROC recv_internal + DECLPROC recv_external + 85143 DECLMETHOD seqno + recv_internal PROC:<{ + // in_msg + DROP // + }> + recv_external PROC:<{ + // in_msg + 9 PUSHPOW2 // in_msg _3=512 + LDSLICEX // signature in_msg + DUP // signature in_msg cs + 32 LDU // signature in_msg _9 cs + 32 LDU // signature in_msg _9 _12 cs + 32 LDU // signature in_msg subwallet_id valid_until msg_seqno cs + NOW // signature in_msg subwallet_id valid_until msg_seqno cs _19 + s1 s3 XCHG // signature in_msg subwallet_id cs msg_seqno valid_until _19 + LEQ // signature in_msg subwallet_id cs msg_seqno _20 + 35 THROWIF + c4 PUSH // signature in_msg subwallet_id cs msg_seqno _23 + CTOS // signature in_msg subwallet_id cs msg_seqno ds + 32 LDU // signature in_msg subwallet_id cs msg_seqno _28 ds + 32 LDU // signature in_msg subwallet_id cs msg_seqno _28 _31 ds + 256 LDU // signature in_msg subwallet_id cs msg_seqno stored_seqno stored_subwallet public_key ds + ENDS + s3 s2 XCPU // signature in_msg subwallet_id cs public_key stored_seqno stored_subwallet msg_seqno stored_seqno + EQUAL // signature in_msg subwallet_id cs public_key stored_seqno stored_subwallet _39 + 33 THROWIFNOT + s4 s4 XCPU // signature in_msg stored_subwallet cs public_key stored_seqno subwallet_id stored_subwallet + EQUAL // signature in_msg stored_subwallet cs public_key stored_seqno _42 + 34 THROWIFNOT + s0 s4 XCHG // signature stored_seqno stored_subwallet cs public_key in_msg + HASHSU // signature stored_seqno stored_subwallet cs public_key _45 + s0 s5 s5 XC2PU // public_key stored_seqno stored_subwallet cs _45 signature public_key + CHKSIGNU // public_key stored_seqno stored_subwallet cs _46 + 35 THROWIFNOT + LDDICT // public_key stored_seqno stored_subwallet dict cs + ENDS + ACCEPT + -1 PUSHINT // public_key stored_seqno stored_subwallet dict i=-1 + UNTIL:<{ + OVER + 16 PUSHINT // public_key stored_seqno stored_subwallet dict i dict _57=16 + DICTIGETNEXT + NULLSWAPIFNOT + NULLSWAPIFNOT // public_key stored_seqno stored_subwallet dict cs i f + DUP // public_key stored_seqno stored_subwallet dict cs i f f + IF:<{ // public_key stored_seqno stored_subwallet dict cs i f + s0 s2 XCHG // public_key stored_seqno stored_subwallet dict f i cs + 8 LDU // public_key stored_seqno stored_subwallet dict f i mode cs + LDREF // public_key stored_seqno stored_subwallet dict f i mode _100 _99 + DROP // public_key stored_seqno stored_subwallet dict f i mode _63 + SWAP // public_key stored_seqno stored_subwallet dict f i _63 mode + SENDRAWMSG + }>ELSE<{ + s2 POP // public_key stored_seqno stored_subwallet dict f i + }> + SWAP // public_key stored_seqno stored_subwallet dict i f + NOT // public_key stored_seqno stored_subwallet dict i _66 + }> // public_key stored_seqno stored_subwallet dict i + 2DROP // public_key stored_seqno stored_subwallet + SWAP // public_key stored_subwallet stored_seqno + INC // public_key stored_subwallet _68 + NEWC // public_key stored_subwallet _68 _69 + 32 STU // public_key stored_subwallet _71 + 32 STU // public_key _73 + 256 STU // _75 + ENDC // _76 + c4 POP + }> + seqno PROC:<{ + // + c4 PUSH // _0 + CTOS // _1 + 32 PLDU // _3 + }> +}END>c diff --git a/submodules/ton/tonlib-src/crypto/smartcont/highload-wallet-v2-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/highload-wallet-v2-code.fif new file mode 100644 index 00000000000..9d5e467de5a --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/highload-wallet-v2-code.fif @@ -0,0 +1,134 @@ +// automatically generated from `smartcont/stdlib.fc` `smartcont/highload-wallet-v2-code.fc` +PROGRAM{ + DECLPROC recv_internal + DECLPROC recv_external + 117746 DECLMETHOD processed? + recv_internal PROC:<{ + // in_msg + DROP // + }> + recv_external PROC:<{ + // in_msg + 9 PUSHPOW2 // in_msg _3=512 + LDSLICEX // signature in_msg + DUP // signature in_msg cs + 32 LDU // signature in_msg _8 cs + 64 LDU // signature in_msg subwallet_id query_id cs + NOW // signature in_msg subwallet_id query_id cs _15 + 32 LSHIFT# // signature in_msg subwallet_id query_id cs bound + s2 s0 PUSH2 // signature in_msg subwallet_id query_id cs bound query_id bound + LESS // signature in_msg subwallet_id query_id cs bound _19 + 35 THROWIF + c4 PUSH // signature in_msg subwallet_id query_id cs bound _22 + CTOS // signature in_msg subwallet_id query_id cs bound ds + 32 LDU // signature in_msg subwallet_id query_id cs bound _28 ds + 64 LDU // signature in_msg subwallet_id query_id cs bound _28 _31 ds + 256 LDU // signature in_msg subwallet_id query_id cs bound _28 _31 _34 ds + LDDICT // signature in_msg subwallet_id query_id cs bound stored_subwallet last_cleaned public_key old_queries ds + ENDS + s6 s0 PUSH2 + 64 PUSHINT // signature in_msg subwallet_id query_id cs bound stored_subwallet last_cleaned public_key old_queries query_id old_queries _42=64 + DICTUGET + NULLSWAPIFNOT // signature in_msg subwallet_id query_id cs bound stored_subwallet last_cleaned public_key old_queries _115 _116 + NIP // signature in_msg subwallet_id query_id cs bound stored_subwallet last_cleaned public_key old_queries found? + 32 THROWIF + s7 s3 XCPU // signature in_msg old_queries query_id cs bound stored_subwallet last_cleaned public_key subwallet_id stored_subwallet + EQUAL // signature in_msg old_queries query_id cs bound stored_subwallet last_cleaned public_key _47 + 34 THROWIFNOT + s0 s7 XCHG // signature public_key old_queries query_id cs bound stored_subwallet last_cleaned in_msg + HASHSU // signature public_key old_queries query_id cs bound stored_subwallet last_cleaned _50 + s0 s8 s7 XC2PU // last_cleaned public_key old_queries query_id cs bound stored_subwallet _50 signature public_key + CHKSIGNU // last_cleaned public_key old_queries query_id cs bound stored_subwallet _51 + 35 THROWIFNOT + s0 s2 XCHG // last_cleaned public_key old_queries query_id stored_subwallet bound cs + LDDICT // last_cleaned public_key old_queries query_id stored_subwallet bound dict cs + ENDS + ACCEPT + -1 PUSHINT // last_cleaned public_key old_queries query_id stored_subwallet bound dict i=-1 + UNTIL:<{ + OVER + 16 PUSHINT // last_cleaned public_key old_queries query_id stored_subwallet bound dict i dict _62=16 + DICTIGETNEXT + NULLSWAPIFNOT + NULLSWAPIFNOT // last_cleaned public_key old_queries query_id stored_subwallet bound dict cs i f + DUP // last_cleaned public_key old_queries query_id stored_subwallet bound dict cs i f f + IF:<{ // last_cleaned public_key old_queries query_id stored_subwallet bound dict cs i f + s0 s2 XCHG // last_cleaned public_key old_queries query_id stored_subwallet bound dict f i cs + 8 LDU // last_cleaned public_key old_queries query_id stored_subwallet bound dict f i mode cs + LDREF // last_cleaned public_key old_queries query_id stored_subwallet bound dict f i mode _125 _124 + DROP // last_cleaned public_key old_queries query_id stored_subwallet bound dict f i mode _68 + SWAP // last_cleaned public_key old_queries query_id stored_subwallet bound dict f i _68 mode + SENDRAWMSG + }>ELSE<{ + s2 POP // last_cleaned public_key old_queries query_id stored_subwallet bound dict f i + }> + SWAP // last_cleaned public_key old_queries query_id stored_subwallet bound dict i f + NOT // last_cleaned public_key old_queries query_id stored_subwallet bound dict i _71 + }> // last_cleaned public_key old_queries query_id stored_subwallet bound dict i + 2DROP // last_cleaned public_key old_queries query_id stored_subwallet bound + 38 PUSHPOW2 // last_cleaned public_key old_queries query_id stored_subwallet bound _74 + SUB // last_cleaned public_key old_queries query_id stored_subwallet bound + NEWC // last_cleaned public_key old_queries query_id stored_subwallet bound _77 + s0 s3 s4 XCHG3 + 64 PUSHINT // last_cleaned public_key stored_subwallet bound _77 query_id old_queries _78=64 + DICTUSETB // last_cleaned public_key stored_subwallet bound old_queries + UNTIL:<{ + DUP + 64 PUSHINT // last_cleaned public_key stored_subwallet bound old_queries old_queries _85=64 + DICTUREMMIN + NULLSWAPIFNOT + NULLSWAPIFNOT // last_cleaned public_key stored_subwallet bound old_queries _126 _128 _127 _129 + s2 POP // last_cleaned public_key stored_subwallet bound old_queries old_queries' f i + s1 s0 XCPU // last_cleaned public_key stored_subwallet bound old_queries old_queries' i f f + IF:<{ // last_cleaned public_key stored_subwallet bound old_queries old_queries' i f + DROP // last_cleaned public_key stored_subwallet bound old_queries old_queries' i + s0 s3 PUSH2 // last_cleaned public_key stored_subwallet bound old_queries old_queries' i i bound + LESS // last_cleaned public_key stored_subwallet bound old_queries old_queries' i f + }> // last_cleaned public_key stored_subwallet bound old_queries old_queries' i f + DUP // last_cleaned public_key stored_subwallet bound old_queries old_queries' i f f + IF:<{ // last_cleaned public_key stored_subwallet bound old_queries old_queries' i f + s3 POP + s6 POP // last_cleaned public_key stored_subwallet bound f old_queries + }>ELSE<{ + s3 s1 s3 XCHG3 + 2DROP // last_cleaned public_key stored_subwallet bound f old_queries + }> + SWAP // last_cleaned public_key stored_subwallet bound old_queries f + NOT // last_cleaned public_key stored_subwallet bound old_queries _90 + }> // last_cleaned public_key stored_subwallet bound old_queries + NIP // last_cleaned public_key stored_subwallet old_queries + NEWC // last_cleaned public_key stored_subwallet old_queries _91 + s1 s2 XCHG // last_cleaned public_key old_queries stored_subwallet _91 + 32 STU // last_cleaned public_key old_queries _93 + s1 s3 XCHG // old_queries public_key last_cleaned _93 + 64 STU // old_queries public_key _95 + 256 STU // old_queries _97 + STDICT // _98 + ENDC // _99 + c4 POP + }> + processed? PROC:<{ + // query_id + c4 PUSH // query_id _2 + CTOS // query_id ds + 32 LDU // query_id _29 _28 + NIP // query_id ds + 64 LDU // query_id _11 ds + 256 LDU // query_id _11 _33 _32 + NIP // query_id _11 ds + LDDICT // query_id last_cleaned old_queries ds + ENDS + s2 s(-1) PUXC + 64 PUSHINT // query_id last_cleaned query_id old_queries _22=64 + DICTUGET + NULLSWAPIFNOT // query_id last_cleaned _36 _37 + NIP // query_id last_cleaned found + IF:<{ // query_id last_cleaned + 2DROP // + TRUE // _24 + }>ELSE<{ // query_id last_cleaned + LEQ // _26 + NEGATE // _24 + }> + }> +}END>c diff --git a/submodules/ton/tonlib-src/crypto/smartcont/new-restricted-wallet2.fif b/submodules/ton/tonlib-src/crypto/smartcont/new-restricted-wallet2.fif index 8f95e4c1cc5..90f544953d4 100644 --- a/submodules/ton/tonlib-src/crypto/smartcont/new-restricted-wallet2.fif +++ b/submodules/ton/tonlib-src/crypto/smartcont/new-restricted-wallet2.fif @@ -29,8 +29,8 @@ def? $3 { @' $3 } { "rwallet" } cond constant file-base } : make-rdict // Create new restricted wallet; code taken from `auto/restricted-wallet2-code.fif` -"auto/restricted-wallet-code.fif" include // code - // data +"auto/restricted-wallet2-code.fif" include // code + // data null // no libraries // create StateInit dup ."StateInit: " b_sig:Maybe msg:Message = SignedMessage; +;; checks signatures and unwap message. +(slice, (int, int)) unwrap_signatures(slice cs, int a_key, int b_key) { + int a? = cs~load_int(1); + slice a_sig = cs; + if (a?) { + a_sig = cs~load_ref().begin_parse().preload_bits(512); + } + var b? = cs~load_int(1); + slice b_sig = cs; + if (b?) { + b_sig = cs~load_ref().begin_parse().preload_bits(512); + } + int hash = cs.slice_hash(); + if (a?) { + throw_unless(err:wrong_a_signature(), check_signature(hash, a_sig, a_key)); + } + if (b?) { + throw_unless(err:wrong_b_signature(), check_signature(hash, b_sig, b_key)); + } + return (cs, (a?, b?)); +} + +;; process message, give state is stateInit +;; +;; stateInit signed_A?:Bool signed_B?:Bool min_A:Grams min_B:Grams expire_at:uint32 A:Grams B:Grams = State; +_ unpack_state_init(slice state) { + return ( + state~load_int(1), + state~load_int(1), + state~load_grams(), + state~load_grams(), + state~load_uint(32), + state~load_grams(), + state~load_grams()); + +} +_ pack_state_init(int signed_A?, int signed_B?, int min_A, int min_B, int expire_at, int A, int B) { + return begin_cell() + .store_int(state:init(), 3) + .store_int(signed_A?, 1) + .store_int(signed_B?, 1) + .store_grams(min_A) + .store_grams(min_B) + .store_uint(expire_at, 32) + .store_grams(A) + .store_grams(B).end_cell(); +} + +;; stateClosing$10 signed_A?:bool signed_B?:Bool promise_A:Grams promise_B:Grams exipire_at:uint32 A:Grams B:Grams = State; +_ unpack_state_close(slice state) { + return ( + state~load_int(1), + state~load_int(1), + state~load_grams(), + state~load_grams(), + state~load_uint(32), + state~load_grams(), + state~load_grams()); +} + +_ pack_state_close(int signed_A?, int signed_B?, int promise_A, int promise_B, int expire_at, int A, int B) { + return begin_cell() + .store_int(state:close(), 3) + .store_int(signed_A?, 1) + .store_int(signed_B?, 1) + .store_grams(promise_A) + .store_grams(promise_B) + .store_uint(expire_at, 32) + .store_grams(A) + .store_grams(B).end_cell(); +} + +_ send_payout(slice s_addr, int amount, int channel_id, int flags) impure { + send_raw_message(begin_cell() + .store_uint(0x10, 6) + .store_slice(s_addr) + .store_grams(amount) + .store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1) + .store_uint(msg:payout(), 32) + .store_uint(channel_id, 64) + .end_cell(), flags); +} + + +cell do_payout(int promise_A, int promise_B, int A, int B, slice a_addr, slice b_addr, int channel_id) impure { + accept_message(); + + int diff = promise_B - promise_A; + if (diff < - A) { + diff = - A; + } + if (diff > B) { + diff = B; + } + A += diff; + B -= diff; + + send_payout(a_addr, A, channel_id, 3); + send_payout(b_addr, B, channel_id, 3); + + return begin_cell() + .store_int(state:payout(), 3) + .store_grams(A) + .store_grams(B) + .end_cell(); +} + + +;; +;; init$000 inc_A:Grams inc_B:Grams min_A:Grams min_B:Grams = Message; +;; +cell with_init(slice state, int msg_value, slice msg, int msg_signed_A?, int msg_signed_B?, + slice a_addr, slice b_addr, int init_timeout, int channel_id) { + ;; parse state + (int signed_A?, int signed_B?, int min_A, int min_B, int expire_at, int A, int B) = unpack_state_init(state); + + if (expire_at == 0) { + expire_at = now() + init_timeout; + } + + int op = msg~load_uint(32); + if (op == msg:timeout()) { + throw_unless(err:no_timeout(), expire_at < now()); + return do_payout(0, 0, A, B, a_addr, b_addr, channel_id); + } + throw_unless(err:expected_init(), op == msg:init()); + + ;; unpack init message + (int inc_A, int inc_B, int upd_min_A, int upd_min_B, int got_channel_id) = + (msg~load_grams(), msg~load_grams(), msg~load_grams(), msg~load_grams(), msg~load_uint(64)); + throw_unless(err:wrong_channel_id(), got_channel_id == channel_id); + + ;; TODO: we should reserve some part of the value for comission + throw_if(err:msg_value_too_small(), msg_value < inc_A + inc_B); + throw_unless(err:replay_protection(), (msg_signed_A? < signed_A?) | (msg_signed_B? < signed_B?)); + + A += inc_A; + B += inc_B; + + signed_A? |= msg_signed_A?; + if (min_A < upd_min_A) { + min_A = upd_min_A; + } + + signed_B? |= msg_signed_B?; + if (min_B < upd_min_B) { + min_B = upd_min_B; + } + + if (signed_A? & signed_B?) { + if ((min_A > A) | (min_B > B)) { + return do_payout(0, 0, A, B, a_addr, b_addr, channel_id); + } + + return pack_state_close(0, 0, 0, 0, 0, A, B); + } + + return pack_state_init(signed_A?, signed_B?, min_A, min_B, expire_at, A, B); +} + +;; close$001 extra_A:Grams extra_B:Grams sig:Maybe promise_A:Grams promise_B:Grams = Message; + +cell with_close(slice cs, slice msg, int msg_signed_A?, int msg_signed_B?, int a_key, int b_key, + slice a_addr, slice b_addr, int expire_timeout, int channel_id) { + ;; parse state + (int signed_A?, int signed_B?, int promise_A, int promise_B, int expire_at, int A, int B) = unpack_state_close(cs); + + if (expire_at == 0) { + expire_at = now() + expire_timeout; + } + + int op = msg~load_uint(32); + if (op == msg:timeout()) { + throw_unless(err:no_timeout(), expire_at < now()); + return do_payout(promise_A, promise_B, A, B, a_addr, b_addr, channel_id); + } + throw_unless(err:expected_close(), op == msg:close()); + + ;; also ensures that (msg_signed_A? | msg_signed_B?) is true + throw_unless(err:replay_protection(), (msg_signed_A? < signed_A?) | (msg_signed_B? < signed_B?)); + signed_A? |= msg_signed_A?; + signed_B? |= msg_signed_B?; + + ;; unpack close message + (int extra_A, int extra_B) = (msg~load_grams(), msg~load_grams()); + int has_sig = msg~load_int(1); + if (has_sig) { + slice sig = msg~load_ref().begin_parse().preload_bits(512); + int hash = msg.slice_hash(); + ifnot (msg_signed_A?) { + throw_unless(err:wrong_a_signature(), check_signature(hash, sig, a_key)); + extra_A = 0; + } + ifnot (msg_signed_B?) { + throw_unless(err:wrong_b_signature(), check_signature(hash, sig, b_key)); + extra_B = 0; + } + } else { + throw_unless(err:no_promise_signature(), msg_signed_A? & msg_signed_B?); + extra_A = 0; + extra_B = 0; + } + (int got_channel_id, int update_promise_A, int update_promise_B) = (msg~load_uint(64), msg~load_grams(), msg~load_grams()); + throw_unless(err:wrong_channel_id(), got_channel_id == channel_id); + + + accept_message(); + update_promise_A += extra_A; + if (promise_A < update_promise_A) { + promise_A = update_promise_A; + } + update_promise_B += extra_B; + if (promise_B < update_promise_B) { + promise_B = update_promise_B; + } + + if (signed_A? & signed_B?) { + return do_payout(promise_A, promise_B, A, B, a_addr, b_addr, channel_id); + } + return pack_state_close(signed_A?, signed_B?, promise_A, promise_B, expire_at, A, B); +} + +() recv_any(int msg_value, slice msg) impure { + (cell config, cell state) = unpack_data(); + (int init_timeout, int close_timeout, int a_key, int b_key, slice a_addr, slice b_addr, int channel_id) = config.unpack_config(); + (int msg_signed_A?, int msg_signed_B?) = msg~unwrap_signatures(a_key, b_key); + + slice cs = state.begin_parse(); + int state_type = cs~load_uint(3); + + if (state_type == state:init()) { ;; init + state = with_init(cs, msg_value, msg, msg_signed_A?, msg_signed_B?, a_addr, b_addr, init_timeout, channel_id); + } if (state_type == state:close()) { + state = with_close(cs, msg, msg_signed_A?, msg_signed_B?, a_key, b_key, a_addr, b_addr, close_timeout, channel_id); + } + + pack_data(config, state); +} + +() recv_internal(int msg_value, cell in_msg_cell, slice in_msg) impure { + recv_any(msg_value, in_msg); +} + +() recv_external(slice in_msg) impure { + recv_any(0, in_msg); +} diff --git a/submodules/ton/tonlib-src/crypto/smartcont/restricted-wallet2-code.fc b/submodules/ton/tonlib-src/crypto/smartcont/restricted-wallet2-code.fc index 8d509886e16..fbad6c09284 100644 --- a/submodules/ton/tonlib-src/crypto/smartcont/restricted-wallet2-code.fc +++ b/submodules/ton/tonlib-src/crypto/smartcont/restricted-wallet2-code.fc @@ -1,13 +1,16 @@ ;; Restricted wallet (a variant of wallet-code.fc) -;; until configuration parameter -13 is set, accepts messages only to elector smc +;; restricts access to parts of balance until certain dates () recv_internal(slice in_msg) impure { ;; do nothing for internal messages } -_ days_passed() inline { - var p = config_param(-13); - return null?(p) ? -1 : (now() - begin_parse(p).preload_uint(32)) / 86400; +_ seconds_passed(int start_at, int utime) inline_ref { + ifnot (start_at) { + var p = config_param(-13); + start_at = null?(p) ? 0 : begin_parse(p).preload_uint(32); + } + return start_at ? utime - start_at : -1; } () recv_external(slice in_msg) impure { @@ -16,7 +19,7 @@ _ days_passed() inline { var (msg_seqno, valid_until) = (cs~load_uint(32), cs~load_uint(32)); throw_if(35, valid_until <= now()); var ds = get_data().begin_parse(); - var (stored_seqno, public_key, rdict) = (ds~load_uint(32), ds~load_uint(256), ds~load_dict()); + var (stored_seqno, public_key, start_at, rdict) = (ds~load_uint(32), ds~load_uint(256), ds~load_uint(32), ds~load_dict()); ds.end_parse(); throw_unless(33, msg_seqno == stored_seqno); ifnot (msg_seqno) { @@ -24,14 +27,15 @@ _ days_passed() inline { set_data(begin_cell() .store_uint(stored_seqno + 1, 32) .store_uint(public_key, 256) + .store_uint(start_at, 32) .store_dict(rdict) .end_cell()); return (); } throw_unless(34, check_signature(slice_hash(in_msg), signature, public_key)); accept_message(); - var ts = days_passed(); - var (_, value, found) = rdict.idict_get_preveq?(16, ts); + var ts = seconds_passed(start_at, now()); + var (_, value, found) = rdict.idict_get_preveq?(32, ts); if (found) { raw_reserve(value~load_grams(), 2); } @@ -45,6 +49,7 @@ _ days_passed() inline { set_data(begin_cell() .store_uint(stored_seqno + 1, 32) .store_uint(public_key, 256) + .store_uint(start_at, 32) .store_dict(rdict) .end_cell()); } @@ -61,15 +66,23 @@ int get_public_key() method_id { return cs.preload_uint(256); } -int balance() method_id { +int compute_balance_at(int utime) inline_ref { var ds = get_data().begin_parse().skip_bits(32 + 256); - var rdict = ds~load_dict(); + var (start_at, rdict) = (ds~load_uint(32), ds~load_dict()); ds.end_parse(); - var ts = days_passed(); + var ts = seconds_passed(start_at, utime); var balance = get_balance().pair_first(); - var (_, value, found) = rdict.idict_get_preveq?(16, ts); + var (_, value, found) = rdict.idict_get_preveq?(32, ts); if (found) { balance = max(balance - value~load_grams(), 0); } return balance; } + +int balance_at(int utime) method_id { + return compute_balance_at(utime); +} + +int balance() method_id { + return compute_balance_at(now()); +} diff --git a/submodules/ton/tonlib-src/crypto/smartcont/restricted-wallet3-code.fc b/submodules/ton/tonlib-src/crypto/smartcont/restricted-wallet3-code.fc new file mode 100644 index 00000000000..aab86065479 --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/restricted-wallet3-code.fc @@ -0,0 +1,103 @@ +;; Restricted wallet initialized by a third party (a variant of restricted-wallet2-code.fc) +;; restricts access to parts of balance until certain dates + +() recv_internal(slice in_msg) impure { + ;; do nothing for internal messages +} + +_ seconds_passed(int start_at, int utime) inline_ref { + ifnot (start_at) { + var p = config_param(-13); + start_at = null?(p) ? 0 : begin_parse(p).preload_uint(32); + } + return start_at ? utime - start_at : -1; +} + +() recv_external(slice in_msg) impure { + var signature = in_msg~load_bits(512); + var cs = in_msg; + var (subwallet_id, valid_until, msg_seqno) = (cs~load_uint(32), cs~load_uint(32), cs~load_uint(32)); + throw_if(35, valid_until <= now()); + var ds = get_data().begin_parse(); + var (stored_seqno, stored_subwallet, public_key) = (ds~load_uint(32), ds~load_uint(32), ds~load_uint(256)); + throw_unless(33, msg_seqno == stored_seqno); + throw_unless(34, subwallet_id == stored_subwallet); + throw_unless(36, check_signature(slice_hash(in_msg), signature, public_key)); + ifnot (msg_seqno) { + public_key = ds~load_uint(256); ;; load "final" public key + ds.end_parse(); + cs~touch(); + var (start_at, rdict) = (cs~load_uint(32), cs~load_dict()); + cs.end_parse(); + accept_message(); + set_data(begin_cell() + .store_uint(stored_seqno + 1, 32) + .store_uint(stored_subwallet, 32) + .store_uint(public_key, 256) + .store_uint(start_at, 32) + .store_dict(rdict) + .end_cell()); + return (); + } + var (start_at, rdict) = (ds~load_uint(32), ds~load_dict()); + ds.end_parse(); + accept_message(); + var ts = seconds_passed(start_at, now()); + var (_, value, found) = rdict.idict_get_preveq?(32, ts); + if (found) { + raw_reserve(value~load_grams(), 2); + } + cs~touch(); + while (cs.slice_refs()) { + var mode = cs~load_uint(8); + var msg = cs~load_ref(); + send_raw_message(msg, mode); + } + cs.end_parse(); + set_data(begin_cell() + .store_uint(stored_seqno + 1, 32) + .store_uint(stored_subwallet, 32) + .store_uint(public_key, 256) + .store_uint(start_at, 32) + .store_dict(rdict) + .end_cell()); +} + +;; Get methods + +int seqno() method_id { + return get_data().begin_parse().preload_uint(32); +} + +int wallet_id() method_id { + var ds = get_data().begin_parse(); + ds~load_uint(32); + return ds.preload_uint(32); +} + +int get_public_key() method_id { + var ds = get_data().begin_parse(); + ds~load_uint(32 + 32); + return ds.preload_uint(256); +} + +int compute_balance_at(int utime) inline_ref { + var ds = get_data().begin_parse().skip_bits(32 + 32 + 256); + var (start_at, rdict) = (ds~load_uint(32), ds~load_dict()); + ds.end_parse(); + var ts = seconds_passed(start_at, utime); + var balance = get_balance().pair_first(); + var (_, value, found) = rdict.idict_get_preveq?(32, ts); + if (found) { + balance = max(balance - value~load_grams(), 0); + } + return balance; +} + +int balance_at(int utime) method_id { + return compute_balance_at(utime); +} + +int balance() method_id { + return compute_balance_at(now()); +} diff --git a/submodules/ton/tonlib-src/crypto/smartcont/show-addr.fif b/submodules/ton/tonlib-src/crypto/smartcont/show-addr.fif index 86b314630bb..c421a8790d3 100755 --- a/submodules/ton/tonlib-src/crypto/smartcont/show-addr.fif +++ b/submodules/ton/tonlib-src/crypto/smartcont/show-addr.fif @@ -18,5 +18,7 @@ dup Blen { 32 B>i@ } { drop Basechain } cond constant wallet_wc file-base +".pk" dup file-exists? { dup file>B dup Blen 32 <> abort"Private key must be exactly 32 bytes long" - =: wallet_pk ."Private key available in file " type cr + tuck =: wallet_pk ."Private key available in file " type cr + priv>pub 256 B>u@ + dup ."Corresponding public key is " .pubkey ." = " 64X. cr } { ."Private key file " type ." not found" cr } cond diff --git a/submodules/ton/tonlib-src/crypto/smartcont/simple-wallet-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/simple-wallet-code.fif new file mode 100644 index 00000000000..c052d4b6564 --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/simple-wallet-code.fif @@ -0,0 +1,45 @@ +// automatically generated from `smartcont/stdlib.fc` `smartcont/simple-wallet-code.fc` +PROGRAM{ + DECLPROC recv_internal + DECLPROC recv_external + recv_internal PROC:<{ + // in_msg + DROP // + }> + recv_external PROC:<{ + // in_msg + 9 PUSHPOW2 // in_msg _3=512 + LDSLICEX // signature in_msg + DUP // signature in_msg cs + 32 LDU // signature in_msg msg_seqno cs + c4 PUSH // signature in_msg msg_seqno cs _11 + CTOS // signature in_msg msg_seqno cs cs2 + 32 LDU // signature in_msg msg_seqno cs stored_seqno cs2 + 256 LDU // signature in_msg msg_seqno cs stored_seqno public_key cs2 + ENDS + s3 s1 XCPU // signature in_msg public_key cs stored_seqno msg_seqno stored_seqno + EQUAL // signature in_msg public_key cs stored_seqno _23 + 33 THROWIFNOT + s0 s3 XCHG // signature stored_seqno public_key cs in_msg + HASHSU // signature stored_seqno public_key cs _26 + s0 s4 s2 XC2PU // cs stored_seqno public_key _26 signature public_key + CHKSIGNU // cs stored_seqno public_key _27 + 34 THROWIFNOT + ACCEPT + s2 s0 XCPU // public_key stored_seqno cs cs + SREFS // public_key stored_seqno cs _32 + IF:<{ // public_key stored_seqno cs + 8 LDU // public_key stored_seqno mode cs + LDREF // public_key stored_seqno mode _37 cs + s0 s2 XCHG // public_key stored_seqno cs _37 mode + SENDRAWMSG + }> // public_key stored_seqno cs + ENDS + INC // public_key _42 + NEWC // public_key _42 _43 + 32 STU // public_key _45 + 256 STU // _47 + ENDC // _48 + c4 POP + }> +}END>c diff --git a/submodules/ton/tonlib-src/crypto/smartcont/wallet-code.fif b/submodules/ton/tonlib-src/crypto/smartcont/wallet-code.fif new file mode 100644 index 00000000000..cd9fa5d0f80 --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smartcont/wallet-code.fif @@ -0,0 +1,59 @@ +// automatically generated from `smartcont/stdlib.fc` `smartcont/wallet-code.fc` +PROGRAM{ + DECLPROC recv_internal + DECLPROC recv_external + 85143 DECLMETHOD seqno + recv_internal PROC:<{ + // in_msg + DROP // + }> + recv_external PROC:<{ + // in_msg + 9 PUSHPOW2 // in_msg _3=512 + LDSLICEX // signature in_msg + DUP // signature in_msg cs + 32 LDU // signature in_msg _8 cs + 32 LDU // signature in_msg msg_seqno valid_until cs + NOW // signature in_msg msg_seqno valid_until cs _15 + s1 s2 XCHG // signature in_msg msg_seqno cs valid_until _15 + LEQ // signature in_msg msg_seqno cs _16 + 35 THROWIF + c4 PUSH // signature in_msg msg_seqno cs _19 + CTOS // signature in_msg msg_seqno cs ds + 32 LDU // signature in_msg msg_seqno cs _23 ds + 256 LDU // signature in_msg msg_seqno cs stored_seqno public_key ds + ENDS + s3 s1 XCPU // signature in_msg public_key cs stored_seqno msg_seqno stored_seqno + EQUAL // signature in_msg public_key cs stored_seqno _31 + 33 THROWIFNOT + s0 s3 XCHG // signature stored_seqno public_key cs in_msg + HASHSU // signature stored_seqno public_key cs _34 + s0 s4 s2 XC2PU // cs stored_seqno public_key _34 signature public_key + CHKSIGNU // cs stored_seqno public_key _35 + 34 THROWIFNOT + ACCEPT + s0 s2 XCHG // public_key stored_seqno cs + WHILE:<{ + DUP // public_key stored_seqno cs cs + SREFS // public_key stored_seqno cs _40 + }>DO<{ // public_key stored_seqno cs + 8 LDU // public_key stored_seqno mode cs + LDREF // public_key stored_seqno mode _45 cs + s0 s2 XCHG // public_key stored_seqno cs _45 mode + SENDRAWMSG + }> // public_key stored_seqno cs + ENDS + INC // public_key _50 + NEWC // public_key _50 _51 + 32 STU // public_key _53 + 256 STU // _55 + ENDC // _56 + c4 POP + }> + seqno PROC:<{ + // + c4 PUSH // _0 + CTOS // _1 + 32 PLDU // _3 + }> +}END>c diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/GenericAccount.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/GenericAccount.cpp index 202ff2dce21..91b2edf7652 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/GenericAccount.cpp +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/GenericAccount.cpp @@ -21,6 +21,31 @@ #include "block/block-auto.h" #include "block/block-parse.h" namespace ton { + +namespace smc { +td::Ref pack_grams(td::uint64 amount) { + vm::CellBuilder cb; + block::tlb::t_Grams.store_integer_value(cb, td::BigInt256(amount)); + return vm::load_cell_slice_ref(cb.finalize()); +} + +bool unpack_grams(td::Ref cs, td::uint64& amount) { + td::RefInt256 got; + if (!block::tlb::t_Grams.as_integer_to(cs, got)) { + return false; + } + if (!got->unsigned_fits_bits(63)) { + return false; + } + auto x = got->to_long(); + if (x < 0) { + return false; + } + amount = x; + return true; +} +} // namespace smc + td::Ref GenericAccount::get_init_state(td::Ref code, td::Ref data) noexcept { return vm::CellBuilder() .store_zeroes(2) @@ -47,7 +72,7 @@ void GenericAccount::store_int_message(vm::CellBuilder& cb, const block::StdAddr .store_long(dest_address.workchain, 8) .store_int256(dest_addr, 256); block::tlb::t_Grams.store_integer_value(cb, td::BigInt256(gramms)); - cb.store_zeroes(9 + 64 + 32 + 1 + 1); + cb.store_zeroes(9 + 64 + 32); } td::Ref GenericAccount::create_ext_message(const block::StdAddress& address, td::Ref new_state, diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/GenericAccount.h b/submodules/ton/tonlib-src/crypto/smc-envelope/GenericAccount.h index 27e43e25beb..6100b6dd46a 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/GenericAccount.h +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/GenericAccount.h @@ -23,6 +23,10 @@ #include "SmartContract.h" namespace ton { +namespace smc { +td::Ref pack_grams(td::uint64 amount); +bool unpack_grams(td::Ref cs, td::uint64& amount); +} // namespace smc class GenericAccount { public: static td::Ref get_init_state(td::Ref code, td::Ref data) noexcept; diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/HighloadWallet.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/HighloadWallet.cpp index af529a1bd5e..7996d095f5a 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/HighloadWallet.cpp +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/HighloadWallet.cpp @@ -73,17 +73,11 @@ td::Ref HighloadWallet::make_a_gift_message(const td::Ed25519::Private for (size_t i = 0; i < gifts.size(); i++) { auto& gift = gifts[i]; td::int32 send_mode = 3; - auto gramms = gift.gramms; - if (gramms == -1) { - gramms = 0; + if (gift.gramms == -1) { send_mode += 128; } + auto message_inner = create_int_message(gift); vm::CellBuilder cb; - GenericAccount::store_int_message(cb, gift.destination, gramms); - cb.store_bytes("\0\0\0\0", 4); - vm::CellString::store(cb, gift.message, 35 * 8).ensure(); - auto message_inner = cb.finalize(); - cb = {}; cb.store_long(send_mode, 8).store_ref(message_inner); auto key = messages.integer_key(td::make_refint(i), 16, false); messages.set_builder(key.bits(), 16, cb); diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/HighloadWalletV2.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/HighloadWalletV2.cpp index dbdb52347ac..bae249b417a 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/HighloadWalletV2.cpp +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/HighloadWalletV2.cpp @@ -73,18 +73,11 @@ td::Ref HighloadWalletV2::make_a_gift_message(const td::Ed25519::Priva for (size_t i = 0; i < gifts.size(); i++) { auto& gift = gifts[i]; td::int32 send_mode = 3; - auto gramms = gift.gramms; - if (gramms == -1) { - gramms = 0; + if (gift.gramms == -1) { send_mode += 128; } vm::CellBuilder cb; - GenericAccount::store_int_message(cb, gift.destination, gramms); - cb.store_bytes("\0\0\0\0", 4); - vm::CellString::store(cb, gift.message, 35 * 8).ensure(); - auto message_inner = cb.finalize(); - cb = {}; - cb.store_long(send_mode, 8).store_ref(message_inner); + cb.store_long(send_mode, 8).store_ref(create_int_message(gift)); auto key = messages.integer_key(td::make_refint(i), 16, false); messages.set_builder(key.bits(), 16, cb); } diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/PaymentChannel.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/PaymentChannel.cpp new file mode 100644 index 00000000000..a736792246d --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/PaymentChannel.cpp @@ -0,0 +1,264 @@ +#include "PaymentChannel.h" +#include "GenericAccount.h" +#include "vm/cells.h" +#include "vm/cellslice.h" +#include "Ed25519.h" +#include "block/block-auto.h" +#include "block/block-parse.h" + +#include "SmartContract.h" +#include "SmartContractCode.h" + +namespace ton { +using smc::pack_grams; +using smc::unpack_grams; +namespace pchan { + +td::Ref Config::serialize() const { + block::gen::ChanConfig::Record rec; + + vm::CellBuilder a_addr_cb; + block::tlb::t_MsgAddressInt.store_std_address(a_addr_cb, a_addr); + rec.a_addr = a_addr_cb.finalize_novm(); + + vm::CellBuilder b_addr_cb; + block::tlb::t_MsgAddressInt.store_std_address(b_addr_cb, b_addr); + rec.b_addr = b_addr_cb.finalize_novm(); + + rec.a_key.as_slice().copy_from(a_key); + rec.b_key.as_slice().copy_from(b_key); + rec.init_timeout = init_timeout; + rec.close_timeout = close_timeout; + rec.channel_id = channel_id; + + td::Ref res; + CHECK(tlb::pack_cell(res, rec)); + return res; +} + +td::Ref MsgInit::serialize() const { + block::gen::ChanMsg::Record_chan_msg_init rec; + rec.min_A = pack_grams(min_A); + rec.min_B = pack_grams(min_B); + rec.inc_A = pack_grams(inc_A); + rec.inc_B = pack_grams(inc_B); + rec.channel_id = channel_id; + + td::Ref res; + CHECK(tlb::pack_cell(res, rec)); + return res; +} + +td::Ref Promise::serialize() const { + block::gen::ChanPromise::Record rec; + rec.channel_id = channel_id; + rec.promise_A = pack_grams(promise_A); + rec.promise_B = pack_grams(promise_B); + td::Ref res; + CHECK(tlb::pack_cell(res, rec)); + return res; +} + +td::SecureString sign(const td::Ref& msg, const td::Ed25519::PrivateKey* key) { + return key->sign(msg->get_hash().as_slice()).move_as_ok(); +} + +td::Ref maybe_sign(const td::Ref& msg, const td::Ed25519::PrivateKey* key) { + if (!key) { + return {}; + } + return vm::CellBuilder().store_bytes(sign(msg, key).as_slice()).finalize(); +} + +td::Ref maybe_ref(td::Ref msg) { + vm::CellBuilder cb; + CHECK(cb.store_maybe_ref(msg)); + return vm::load_cell_slice_ref(cb.finalize()); +} + +td::Ref MsgClose::serialize() const { + block::gen::ChanMsg::Record_chan_msg_close rec; + rec.extra_A = pack_grams(extra_A); + rec.extra_B = pack_grams(extra_B); + rec.promise = signed_promise; + + td::Ref res; + CHECK(tlb::pack_cell(res, rec)); + return res; +} + +td::Ref MsgTimeout::serialize() const { + block::gen::ChanMsg::Record_chan_msg_timeout rec; + td::Ref res; + CHECK(tlb::pack_cell(res, rec)); + return res; +} + +td::SecureString SignedPromise::signature(const td::Ed25519::PrivateKey* key, const td::Ref& promise) { + return sign(promise, key); +} +td::Ref SignedPromise::create_and_serialize(td::Slice signature, const td::Ref& promise) { + block::gen::ChanSignedPromise::Record rec; + rec.promise = vm::load_cell_slice_ref(promise); + LOG(ERROR) << "signature.size() = " << signature.size(); + rec.sig = maybe_ref(vm::CellBuilder().store_bytes(signature).finalize()); + td::Ref res; + CHECK(tlb::pack_cell(res, rec)); + return res; +} +td::Ref SignedPromise::create_and_serialize(const td::Ed25519::PrivateKey* key, + const td::Ref& promise) { + block::gen::ChanSignedPromise::Record rec; + rec.promise = vm::load_cell_slice_ref(promise); + rec.sig = maybe_ref(maybe_sign(promise, key)); + td::Ref res; + CHECK(tlb::pack_cell(res, rec)); + return res; +} + +bool SignedPromise::unpack(td::Ref cell) { + block::gen::ChanSignedPromise::Record rec; + if (!tlb::unpack_cell(cell, rec)) { + return false; + } + block::gen::ChanPromise::Record rec_promise; + if (!tlb::csr_unpack(rec.promise, rec_promise)) { + return false; + } + promise.channel_id = rec_promise.channel_id; + if (!unpack_grams(rec_promise.promise_A, promise.promise_A)) { + return false; + } + if (!unpack_grams(rec_promise.promise_B, promise.promise_B)) { + return false; + } + td::Ref sig_cell; + if (!rec.sig->prefetch_maybe_ref(sig_cell)) { + return false; + } + td::SecureString signature(64); + vm::CellSlice cs = vm::load_cell_slice(sig_cell); + if (!cs.prefetch_bytes(signature.as_mutable_slice())) { + return false; + } + o_signature = std::move(signature); + return true; +} + +td::Ref StateInit::serialize() const { + block::gen::ChanState::Record_chan_state_init rec; + rec.expire_at = expire_at; + rec.min_A = pack_grams(min_A); + rec.min_B = pack_grams(min_B); + rec.A = pack_grams(A); + rec.B = pack_grams(B); + rec.signed_A = signed_A; + rec.signed_B = signed_B; + td::Ref res; + CHECK(tlb::pack_cell(res, rec)); + return res; +} + +td::Ref Data::serialize() const { + block::gen::ChanData::Record rec; + rec.config = config; + rec.state = state; + td::Ref res; + CHECK(block::gen::t_ChanData.cell_pack(res, rec)); + return res; +} + +td::Ref Data::init_state() { + return StateInit().serialize(); +} +} // namespace pchan + +td::Result PaymentChannel::get_info() const { + block::gen::ChanData::Record data_rec; + if (!tlb::unpack_cell(get_state().data, data_rec)) { + return td::Status::Error("Can't unpack data"); + } + block::gen::ChanConfig::Record config_rec; + if (!tlb::unpack_cell(data_rec.config, config_rec)) { + return td::Status::Error("Can't unpack config"); + } + pchan::Config config; + config.a_key = td::SecureString(config_rec.a_key.as_slice()); + config.b_key = td::SecureString(config_rec.b_key.as_slice()); + block::tlb::t_MsgAddressInt.extract_std_address(vm::load_cell_slice_ref(config_rec.a_addr), config.a_addr); + block::tlb::t_MsgAddressInt.extract_std_address(vm::load_cell_slice_ref(config_rec.b_addr), config.b_addr); + config.init_timeout = static_cast(config_rec.init_timeout); + config.close_timeout = static_cast(config_rec.close_timeout); + config.channel_id = static_cast(config_rec.channel_id); + + auto state_cs = vm::load_cell_slice(data_rec.state); + Info res; + switch (block::gen::t_ChanState.check_tag(state_cs)) { + case block::gen::ChanState::chan_state_init: { + pchan::StateInit state; + block::gen::ChanState::Record_chan_state_init state_rec; + if (!tlb::unpack_cell(data_rec.state, state_rec)) { + return td::Status::Error("Can't unpack state"); + } + bool ok = unpack_grams(state_rec.A, state.A) && unpack_grams(state_rec.B, state.B) && + unpack_grams(state_rec.min_A, state.min_A) && unpack_grams(state_rec.min_B, state.min_B); + state.expire_at = state_rec.expire_at; + state.signed_A = state_rec.signed_A; + state.signed_B = state_rec.signed_B; + if (!ok) { + return td::Status::Error("Can't unpack state"); + } + res.state = std::move(state); + break; + } + case block::gen::ChanState::chan_state_close: { + pchan::StateClose state; + block::gen::ChanState::Record_chan_state_close state_rec; + if (!tlb::unpack_cell(data_rec.state, state_rec)) { + return td::Status::Error("Can't unpack state"); + } + bool ok = unpack_grams(state_rec.A, state.A) && unpack_grams(state_rec.B, state.B) && + unpack_grams(state_rec.promise_A, state.promise_A) && + unpack_grams(state_rec.promise_B, state.promise_B); + state.expire_at = state_rec.expire_at; + state.signed_A = state_rec.signed_A; + state.signed_B = state_rec.signed_B; + if (!ok) { + return td::Status::Error("Can't unpack state"); + } + res.state = std::move(state); + break; + } + case block::gen::ChanState::chan_state_payout: { + pchan::StatePayout state; + block::gen::ChanState::Record_chan_state_payout state_rec; + if (!tlb::unpack_cell(data_rec.state, state_rec)) { + return td::Status::Error("Can't unpack state"); + } + bool ok = unpack_grams(state_rec.A, state.A) && unpack_grams(state_rec.B, state.B); + if (!ok) { + return td::Status::Error("Can't unpack state"); + } + res.state = std::move(state); + break; + } + default: + return td::Status::Error("Can't unpack state"); + } + + res.config = std::move(config); + res.description = block::gen::t_ChanState.as_string_ref(data_rec.state); + + return std::move(res); +} // namespace ton + +td::optional PaymentChannel::guess_revision(const vm::Cell::Hash& code_hash) { + for (auto i : ton::SmartContractCode::get_revisions(ton::SmartContractCode::PaymentChannel)) { + auto code = SmartContractCode::get_code(SmartContractCode::PaymentChannel, i); + if (code->get_hash() == code_hash) { + return i; + } + } + return {}; +} +} // namespace ton diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/PaymentChannel.h b/submodules/ton/tonlib-src/crypto/smc-envelope/PaymentChannel.h new file mode 100644 index 00000000000..f050f330529 --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/PaymentChannel.h @@ -0,0 +1,251 @@ +#pragma once +#include "vm/cells.h" +#include "vm/cellslice.h" +#include "Ed25519.h" +#include "block/block-auto.h" +#include "block/block-parse.h" + +#include "td/utils/Variant.h" + +#include "SmartContract.h" +#include "SmartContractCode.h" + +namespace ton { +namespace pchan { + +// +// Payment channels +// +struct Config { + td::uint32 init_timeout{0}; + td::uint32 close_timeout{0}; + td::SecureString a_key; + td::SecureString b_key; + block::StdAddress a_addr; + block::StdAddress b_addr; + td::uint64 channel_id{0}; + + td::Ref serialize() const; +}; + +struct MsgInit { + td::uint64 inc_A{0}; + td::uint64 inc_B{0}; + td::uint64 min_A{0}; + td::uint64 min_B{0}; + td::uint64 channel_id{0}; + + td::Ref serialize() const; +}; + +struct Promise { + td::uint64 channel_id; + td::uint64 promise_A{0}; + td::uint64 promise_B{0}; + td::Ref serialize() const; +}; + +td::Ref maybe_sign(const td::Ref& msg, const td::Ed25519::PrivateKey* key); +td::Ref maybe_ref(td::Ref msg); + +struct MsgClose { + td::uint64 extra_A{0}; + td::uint64 extra_B{0}; + td::Ref signed_promise; + td::Ref serialize() const; +}; + +struct MsgTimeout { + td::Ref serialize() const; +}; + +struct SignedPromise { + Promise promise; + td::optional o_signature; + + bool unpack(td::Ref cell); + static td::SecureString signature(const td::Ed25519::PrivateKey* key, const td::Ref& promise); + static td::Ref create_and_serialize(td::Slice signature, const td::Ref& promise); + static td::Ref create_and_serialize(const td::Ed25519::PrivateKey* key, const td::Ref& promise); +}; + +struct StateInit { + bool signed_A{false}; + bool signed_B{false}; + td::uint64 min_A{0}; + td::uint64 min_B{0}; + td::uint64 A{0}; + td::uint64 B{0}; + td::uint32 expire_at{0}; + + td::Ref serialize() const; +}; + +struct StateClose { + bool signed_A{false}; + bool signed_B{false}; + td::uint64 promise_A{0}; + td::uint64 promise_B{0}; + td::uint64 A{0}; + td::uint64 B{0}; + td::uint32 expire_at{0}; +}; + +struct StatePayout { + td::uint64 A{0}; + td::uint64 B{0}; +}; + +struct Data { + td::Ref config; + td::Ref state; + + static td::Ref init_state(); + + td::Ref serialize() const; +}; + +template +struct MsgBuilder { + td::Ed25519::PrivateKey* a_key{nullptr}; + td::Ed25519::PrivateKey* b_key{nullptr}; + + T&& with_a_key(td::Ed25519::PrivateKey* key) && { + a_key = key; + return static_cast(*this); + } + T&& with_b_key(td::Ed25519::PrivateKey* key) && { + b_key = key; + return static_cast(*this); + } + + td::Ref finalize() && { + block::gen::ChanSignedMsg::Record rec; + auto msg = static_cast(*this).msg.serialize(); + rec.msg = vm::load_cell_slice_ref(msg); + rec.sig_A = maybe_ref(maybe_sign(msg, a_key)); + rec.sig_B = maybe_ref(maybe_sign(msg, b_key)); + td::Ref res; + CHECK(tlb::pack_cell(res, rec)); + return res; + } +}; + +struct MsgInitBuilder : public MsgBuilder { + MsgInit msg; + + MsgInitBuilder&& min_A(td::uint64 value) && { + msg.min_A = value; + return std::move(*this); + } + MsgInitBuilder&& min_B(td::uint64 value) && { + msg.min_B = value; + return std::move(*this); + } + MsgInitBuilder&& inc_A(td::uint64 value) && { + msg.inc_A = value; + return std::move(*this); + } + MsgInitBuilder&& inc_B(td::uint64 value) && { + msg.inc_B = value; + return std::move(*this); + } + MsgInitBuilder&& channel_id(td::uint64 value) && { + msg.channel_id = value; + return std::move(*this); + } +}; + +struct MsgTimeoutBuilder : public MsgBuilder { + MsgTimeout msg; +}; + +struct MsgCloseBuilder : public MsgBuilder { + MsgClose msg; + + MsgCloseBuilder&& extra_A(td::uint64 value) && { + msg.extra_A = value; + return std::move(*this); + } + MsgCloseBuilder&& extra_B(td::uint64 value) && { + msg.extra_B = value; + return std::move(*this); + } + MsgCloseBuilder&& signed_promise(td::Ref signed_promise) && { + msg.signed_promise = vm::load_cell_slice_ref(signed_promise); + return std::move(*this); + } +}; + +struct SignedPromiseBuilder { + Promise promise; + td::optional o_signature; + td::Ed25519::PrivateKey* key{nullptr}; + + SignedPromiseBuilder& with_key(td::Ed25519::PrivateKey* key) { + this->key = key; + return *this; + } + SignedPromiseBuilder& promise_A(td::uint64 value) { + promise.promise_A = value; + return *this; + } + SignedPromiseBuilder& promise_B(td::uint64 value) { + promise.promise_B = value; + return *this; + } + SignedPromiseBuilder& channel_id(td::uint64 value) { + promise.channel_id = value; + return *this; + } + SignedPromiseBuilder& signature(td::SecureString signature) { + o_signature = std::move(signature); + return *this; + } + + bool check_signature(td::Slice signature, const td::Ed25519::PublicKey& pk) { + return pk.verify_signature(promise.serialize()->get_hash().as_slice(), signature).is_ok(); + } + td::SecureString calc_signature() { + CHECK(key); + return SignedPromise::signature(key, promise.serialize()); + } + td::Ref finalize() { + if (o_signature) { + return SignedPromise::create_and_serialize(o_signature.value().copy(), promise.serialize()); + } else { + return SignedPromise::create_and_serialize(key, promise.serialize()); + } + } +}; + +} // namespace pchan + +class PaymentChannel : public SmartContract { + public: + PaymentChannel(State state) : SmartContract(std::move(state)) { + } + + struct Info { + pchan::Config config; + td::Variant state; + std::string description; + }; + td::Result get_info() const; + + static td::Ref create(State state) { + return td::Ref(true, std::move(state)); + } + static td::optional guess_revision(const vm::Cell::Hash& code_hash); + static td::Ref create(const pchan::Config& config, td::int32 revision) { + State state; + state.code = SmartContractCode::get_code(SmartContractCode::PaymentChannel, revision); + pchan::Data data; + data.config = config.serialize(); + pchan::StateInit init; + data.state = init.serialize(); + state.data = data.serialize(); + return create(std::move(state)); + } +}; +} // namespace ton diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContract.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContract.cpp index 42a6ea8ad47..79a2a8239bf 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContract.cpp +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContract.cpp @@ -32,19 +32,19 @@ namespace ton { namespace { -td::Ref prepare_vm_stack(td::Ref body) { +td::Ref prepare_vm_stack(td::RefInt256 amount, td::Ref body) { td::Ref stack_ref{true}; td::RefInt256 acc_addr{true}; //CHECK(acc_addr.write().import_bits(account.addr.cbits(), 256)); vm::Stack& stack = stack_ref.write(); stack.push_int(td::make_refint(10000000000)); - stack.push_int(td::make_refint(10000000000)); + stack.push_int(std::move(amount)); stack.push_cell(vm::CellBuilder().finalize()); stack.push_cellslice(std::move(body)); return stack_ref; } -td::Ref prepare_vm_c7(td::uint32 now) { +td::Ref prepare_vm_c7(td::uint32 now, td::uint64 balance) { // TODO: fix initialization of c7 td::BitArray<256> rand_seed; rand_seed.as_slice().fill(0); @@ -58,7 +58,7 @@ td::Ref prepare_vm_c7(td::uint32 now) { td::make_refint(0), // block_lt:Integer td::make_refint(0), // trans_lt:Integer std::move(rand_seed_int), // rand_seed:Integer - block::CurrencyCollection(1000000000).as_vm_tuple(), // balance_remaining:[Integer (Maybe Cell)] + block::CurrencyCollection(balance).as_vm_tuple(), // balance_remaining:[Integer (Maybe Cell)] vm::load_cell_slice_ref(vm::CellBuilder().finalize()) // myself:MsgAddressInt //vm::StackEntry::maybe(td::Ref()) ); // global_config:(Maybe Cell) ] = SmartContractInfo; @@ -66,6 +66,15 @@ td::Ref prepare_vm_c7(td::uint32 now) { return vm::make_tuple_ref(std::move(tuple)); } +static int output_actions_count(td::Ref list) { + int i = -1; + do { + ++i; + list = load_cell_slice(std::move(list)).prefetch_ref(); + } while (list.not_null()); + return i; +} + SmartContract::Answer run_smartcont(SmartContract::State state, td::Ref stack, td::Ref c7, vm::GasLimits gas, bool ignore_chksig) { auto gas_credit = gas.gas_credit; @@ -123,6 +132,8 @@ SmartContract::Answer run_smartcont(SmartContract::State state, td::Ref cell, Args args) { - return run_method(args.set_stack(prepare_vm_stack(vm::load_cell_slice_ref(cell))).set_method_id(-1)); + return run_method( + args.set_stack(prepare_vm_stack(td::make_refint(0), vm::load_cell_slice_ref(cell))).set_method_id(-1)); +} +SmartContract::Answer SmartContract::send_internal_message(td::Ref cell, Args args) { + return run_method( + args.set_stack(prepare_vm_stack(td::make_refint(args.amount), vm::load_cell_slice_ref(cell))).set_method_id(0)); } } // namespace ton diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContract.h b/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContract.h index 5bc70a4fe9d..89f5c8c790e 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContract.h +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContract.h @@ -57,6 +57,8 @@ class SmartContract : public td::CntObject { td::optional> stack; td::optional now; bool ignore_chksig{false}; + td::uint64 amount{0}; + td::uint64 balance{0}; Args() { } @@ -95,6 +97,14 @@ class SmartContract : public td::CntObject { this->ignore_chksig = ignore_chksig; return std::move(*this); } + Args&& set_amount(td::uint64 amount) { + this->amount = amount; + return std::move(*this); + } + Args&& set_balance(td::uint64 balance) { + this->balance = balance; + return std::move(*this); + } td::Result get_method_id() const { if (!method_id) { @@ -109,6 +119,7 @@ class SmartContract : public td::CntObject { Answer run_get_method(Args args = {}) const; Answer run_get_method(td::Slice method, Args args = {}) const; Answer send_external_message(td::Ref cell, Args args = {}); + Answer send_internal_message(td::Ref cell, Args args = {}); size_t code_size() const; size_t data_size() const; @@ -122,6 +133,9 @@ class SmartContract : public td::CntObject { const State& get_state() const { return state_; } + CntObject* make_copy() const override { + return new SmartContract(state_); + } protected: State state_; diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContractCode.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContractCode.cpp index 27bf58ab4f6..8d52b41a2ba 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContractCode.cpp +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContractCode.cpp @@ -44,6 +44,8 @@ const auto& get_map() { #include "smartcont/auto/highload-wallet-code.cpp" #include "smartcont/auto/highload-wallet-v2-code.cpp" #include "smartcont/auto/dns-manual-code.cpp" +#include "smartcont/auto/payment-channel-code.cpp" +#include "smartcont/auto/restricted-wallet3-code.cpp" with_tvm_code("highload-wallet-r1", "te6ccgEBBgEAhgABFP8A9KQT9KDyyAsBAgEgAgMCAUgEBQC88oMI1xgg0x/TH9Mf+CMTu/Jj7UTQ0x/TH9P/" @@ -96,6 +98,13 @@ const auto& get_map() { "FwCEMQLTAAHAAZPUAdCY0wUBqgLXGAHiINdJwg/" "ypiB41yLXCwfyaHBTEddJqTYCmNMHAcAAEqEB5DDIywYBzxbJ0FADACBZ9KhvpSCUAvQEMJIybeICACg0A4AQ9FqZECOECUBE8AEBkjAx4gBmM" "SLAFZwy9AQQI4QJUELwAQHgIsAWmDIChAn0czAB4DAyIMAfkzD0BODAIJJtAeDyLG0B"); + with_tvm_code( + "restricted-wallet3-r1", + "te6ccgECEgEAAUwAART/APSkE/S88sgLAQIBIAIDAgFIBAUD+PKDCNcYINMf0x/THwL4I7vyY+1E0NMf0x/T/" + "1NDuvKhUWK68qIG+QFUEHb5EPKkAY4fMwHT/9EB0x/0BNH4AAOkyMsfFMsfy/8Syx/0AMntVOEC0x/" + "0BNH4ACH4I9s8IYAg9HtvpTGW+gAwcvsCkTDiApMg10qK6NECpMgPEBEABNAwAgEgBgcCASAICQIBSAwNAgFuCgsAEbjJftRNDXCx+" + "AAXrc52omhpn5jrhf/AABmsePaiaEAQa5DrhY/AAQ222B8Ee2eQDgEJtQdbZ5AOAU7tRNCBAUDXIdMf9ATRAts8+CdvEAKAIPR7b6Uxl/" + "oAMKFwtgmRMOIPADohjhExgPP4MyBukjBwlNDXCx/iAd8hkgGhklt/4gAM0wfUAvsAAB7LHxTLHxLL/8sf9ADJ7VQ="); return map; }(); return map; @@ -103,7 +112,6 @@ const auto& get_map() { } // namespace td::Result> SmartContractCode::load(td::Slice name) { - LOG(ERROR) << "LOAD " << name; auto& map = get_map(); auto it = map.find(name); if (it == map.end()) { @@ -146,6 +154,14 @@ td::Span SmartContractCode::get_revisions(Type type) { static int res[] = {-1, 1}; return res; } + case Type::PaymentChannel: { + static int res[] = {-1}; + return res; + } + case Type::RestrictedWallet: { + static int res[] = {-1, 1}; + return res; + } } UNREACHABLE(); return {}; @@ -190,6 +206,10 @@ td::Ref SmartContractCode::get_code(Type type, int ext_revision) { return "multisig"; case Type::ManualDns: return "dns-manual"; + case Type::PaymentChannel: + return "payment-channel"; + case Type::RestrictedWallet: + return "restricted-wallet3"; } UNREACHABLE(); return ""; diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContractCode.h b/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContractCode.h index 1ea2274c846..e9ca1c543db 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContractCode.h +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/SmartContractCode.h @@ -16,6 +16,7 @@ Copyright 2017-2020 Telegram Systems LLP */ +#pragma once #include "vm/cells.h" #include "td/utils/Span.h" @@ -25,7 +26,18 @@ class SmartContractCode { public: static td::Result> load(td::Slice name); - enum Type { WalletV1 = 1, WalletV1Ext, WalletV2, WalletV3, HighloadWalletV1, HighloadWalletV2, ManualDns, Multisig }; + enum Type { + WalletV1 = 1, + WalletV1Ext, + WalletV2, + WalletV3, + HighloadWalletV1, + HighloadWalletV2, + ManualDns, + Multisig, + PaymentChannel, + RestrictedWallet + }; static td::Span get_revisions(Type type); static td::Result validate_revision(Type type, int revision); static td::Ref get_code(Type type, int revision = 0); diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/TestGiver.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/TestGiver.cpp index f9ed60bfd73..2a1691835db 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/TestGiver.cpp +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/TestGiver.cpp @@ -43,12 +43,7 @@ td::Ref TestGiver::make_a_gift_message_static(td::uint32 seqno, td::Sp for (auto& gift : gifts) { td::int32 send_mode = 1; - auto gramms = gift.gramms; - vm::CellBuilder cbi; - GenericAccount::store_int_message(cbi, gift.destination, gramms); - store_gift_message(cbi, gift); - auto message_inner = cbi.finalize(); - cb.store_long(send_mode, 8).store_ref(std::move(message_inner)); + cb.store_long(send_mode, 8).store_ref(create_int_message(gift)); } return cb.finalize(); diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/TestWallet.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/TestWallet.cpp index 4f4dcd8dc2d..f218cf7ccf6 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/TestWallet.cpp +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/TestWallet.cpp @@ -46,18 +46,11 @@ td::Ref TestWallet::make_a_gift_message_static(const td::Ed25519::Priv for (auto& gift : gifts) { td::int32 send_mode = 3; - auto gramms = gift.gramms; - if (gramms == -1) { - gramms = 0; + if (gift.gramms == -1) { send_mode += 128; } - vm::CellBuilder cbi; - GenericAccount::store_int_message(cbi, gift.destination, gramms); - store_gift_message(cbi, gift); - auto message_inner = cbi.finalize(); - cb.store_long(send_mode, 8).store_ref(std::move(message_inner)); + cb.store_long(send_mode, 8).store_ref(create_int_message(gift)); } - auto message_outer = cb.finalize(); auto signature = private_key.sign(message_outer->get_hash().as_slice()).move_as_ok(); return vm::CellBuilder().store_bytes(signature).append_cellslice(vm::load_cell_slice(message_outer)).finalize(); diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/Wallet.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/Wallet.cpp index ef637fb96c9..a09ddff9406 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/Wallet.cpp +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/Wallet.cpp @@ -52,16 +52,10 @@ td::Ref Wallet::make_a_gift_message(const td::Ed25519::PrivateKey& pri for (auto& gift : gifts) { td::int32 send_mode = 3; - auto gramms = gift.gramms; - if (gramms == -1) { - gramms = 0; + if (gift.gramms == -1) { send_mode += 128; } - vm::CellBuilder cbi; - GenericAccount::store_int_message(cbi, gift.destination, gramms); - store_gift_message(cbi, gift); - auto message_inner = cbi.finalize(); - cb.store_long(send_mode, 8).store_ref(std::move(message_inner)); + cb.store_long(send_mode, 8).store_ref(create_int_message(gift)); } auto message_outer = cb.finalize(); diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/WalletInterface.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/WalletInterface.cpp new file mode 100644 index 00000000000..2e5809cb2f7 --- /dev/null +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/WalletInterface.cpp @@ -0,0 +1,52 @@ +/* + This file is part of TON Blockchain Library. + + TON Blockchain Library is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + TON Blockchain Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with TON Blockchain Library. If not, see . + + Copyright 2017-2020 Telegram Systems LLP +*/ +#include "WalletInterface.h" + +#include "GenericAccount.h" + +namespace ton { +td::Ref WalletInterfaceRaw::create_int_message(const Gift &gift) { + vm::CellBuilder cbi; + GenericAccount::store_int_message(cbi, gift.destination, gift.gramms < 0 ? 0 : gift.gramms); + if (gift.init_state.not_null()) { + cbi.store_ones(2); + cbi.store_ref(gift.init_state); + } + cbi.store_zeroes(0); + store_gift_message(cbi, gift); + return cbi.finalize(); +} + +td::Result WalletInterfaceRaw::get_public_key() const { + auto sc = as_smart_constract(); + auto answer = sc.run_get_method("get_public_key"); + if (!answer.success) { + return td::Status::Error("get_public_key failed"); + } + auto do_get_public_key = [&]() -> td::Result { + auto key = answer.stack.write().pop_int_finite(); + td::SecureString bytes(32); + if (!key->export_bytes(bytes.as_mutable_slice().ubegin(), bytes.size())) { + return td::Status::Error("get_public_key failed"); + } + return td::Ed25519::PublicKey(std::move(bytes)); + }; + return TRY_VM(do_get_public_key()); +} +} // namespace ton diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/WalletInterface.h b/submodules/ton/tonlib-src/crypto/smc-envelope/WalletInterface.h index c8666f53a32..d4113a6f628 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/WalletInterface.h +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/WalletInterface.h @@ -24,6 +24,7 @@ #include "vm/cells/CellString.h" #include "SmartContract.h" +#include "GenericAccount.h" namespace ton { class WalletInterface { @@ -36,6 +37,7 @@ class WalletInterface { std::string message; td::Ref body; + td::Ref init_state; }; virtual ~WalletInterface() { @@ -48,15 +50,29 @@ class WalletInterface { return td::Status::Error("Unsupported"); } - td::Result> get_init_message(const td::Ed25519::PrivateKey &private_key, - td::uint32 valid_until = std::numeric_limits::max()) { + td::Result> get_init_message( + const td::Ed25519::PrivateKey &private_key, + td::uint32 valid_until = std::numeric_limits::max()) const { return make_a_gift_message(private_key, valid_until, {}); } + static td::Ref create_int_message(const Gift &gift) { + vm::CellBuilder cbi; + GenericAccount::store_int_message(cbi, gift.destination, gift.gramms < 0 ? 0 : gift.gramms); + if (gift.init_state.not_null()) { + cbi.store_ones(2); + cbi.store_ref(gift.init_state); + } else { + cbi.store_zeroes(1); + } + cbi.store_zeroes(1); + store_gift_message(cbi, gift); + return cbi.finalize(); + } static void store_gift_message(vm::CellBuilder &cb, const Gift &gift) { if (gift.body.not_null()) { auto body = vm::load_cell_slice(gift.body); //TODO: handle error - cb.append_cellslice_bool(body); + CHECK(cb.append_cellslice_bool(body)); return; } diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/WalletV3.cpp b/submodules/ton/tonlib-src/crypto/smc-envelope/WalletV3.cpp index 39993c66e6f..5bd7cfcd051 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/WalletV3.cpp +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/WalletV3.cpp @@ -62,16 +62,10 @@ td::Ref WalletV3::make_a_gift_message(const td::Ed25519::PrivateKey& p for (auto& gift : gifts) { td::int32 send_mode = 3; - auto gramms = gift.gramms; - if (gramms == -1) { - gramms = 0; + if (gift.gramms == -1) { send_mode += 128; } - vm::CellBuilder cbi; - GenericAccount::store_int_message(cbi, gift.destination, gramms); - store_gift_message(cbi, gift); - auto message_inner = cbi.finalize(); - cb.store_long(send_mode, 8).store_ref(std::move(message_inner)); + cb.store_long(send_mode, 8).store_ref(create_int_message(gift)); } auto message_outer = cb.finalize(); diff --git a/submodules/ton/tonlib-src/crypto/smc-envelope/WalletV3.h b/submodules/ton/tonlib-src/crypto/smc-envelope/WalletV3.h index c5cfead340d..b3e332ddab7 100644 --- a/submodules/ton/tonlib-src/crypto/smc-envelope/WalletV3.h +++ b/submodules/ton/tonlib-src/crypto/smc-envelope/WalletV3.h @@ -70,3 +70,209 @@ class WalletV3 : public ton::SmartContract, public WalletInterface { td::Result get_public_key_or_throw() const; }; } // namespace ton + +#include "smc-envelope/SmartContractCode.h" +#include "smc-envelope/GenericAccount.h" +#include "block/block-parse.h" +#include +namespace ton { +template +class WalletBase : public SmartContract, public WalletInterface { + public: + using Traits = TraitsT; + using InitData = typename Traits::InitData; + + explicit WalletBase(State state) : SmartContract(std::move(state)) { + } + static td::Ref create(State state) { + return td::Ref(true, std::move(state)); + } + static td::Ref get_init_code(int revision) { + return SmartContractCode::get_code(get_code_type(), revision); + }; + size_t get_max_gifts_size() const override { + return Traits::max_gifts_size; + } + static SmartContractCode::Type get_code_type() { + return Traits::code_type; + } + static td::optional guess_revision(const vm::Cell::Hash& code_hash) { + for (auto i : ton::SmartContractCode::get_revisions(get_code_type())) { + auto code = SmartContractCode::get_code(get_code_type(), i); + if (code->get_hash() == code_hash) { + return i; + } + } + return {}; + } + + static td::Ref create(const InitData& init_data, int revision) { + return td::Ref(true, State{get_init_code(revision), WalletT::get_init_data(init_data)}); + } + + td::Result get_seqno() const { + return TRY_VM([&]() -> td::Result { + Answer answer = this->run_get_method("seqno"); + if (!answer.success) { + return td::Status::Error("seqno get method failed"); + } + return static_cast(answer.stack.write().pop_long_range(std::numeric_limits::max())); + }()); + } + td::Result get_wallet_id() const { + return TRY_VM([&]() -> td::Result { + Answer answer = this->run_get_method("wallet_id"); + if (!answer.success) { + return td::Status::Error("seqno get method failed"); + } + return static_cast(answer.stack.write().pop_long_range(std::numeric_limits::max())); + }()); + } + + td::Result get_balance(td::uint64 account_balance, td::uint32 now) const { + return TRY_VM([&]() -> td::Result { + Answer answer = this->run_get_method(Args().set_method_id("balance").set_balance(account_balance).set_now(now)); + if (!answer.success) { + return td::Status::Error("balance get method failed"); + } + return static_cast(answer.stack.write().pop_long()); + }()); + } + + td::Result get_public_key() const override { + return TRY_VM([&]() -> td::Result { + Answer answer = this->run_get_method("get_public_key"); + if (!answer.success) { + return td::Status::Error("get_public_key get method failed"); + } + auto key_int = answer.stack.write().pop_int(); + LOG(ERROR) << key_int->bit_size(false); + td::SecureString bytes(32); + if (!key_int->export_bytes(bytes.as_mutable_slice().ubegin(), bytes.size(), false)) { + return td::Status::Error("not a public key"); + } + return td::Ed25519::PublicKey(std::move(bytes)); + }()); + }; +}; + +struct RestrictedWalletTraits { + struct InitData { + td::SecureString init_key; + td::SecureString main_key; + td::uint32 wallet_id{0}; + }; + + static constexpr unsigned max_message_size = vm::CellString::max_bytes; + static constexpr unsigned max_gifts_size = 4; + static constexpr auto code_type = SmartContractCode::RestrictedWallet; +}; + +class RestrictedWallet : public WalletBase { + public: + struct Config { + td::uint32 start_at{0}; + std::vector> limits; + }; + + explicit RestrictedWallet(State state) : WalletBase(std::move(state)) { + } + + td::Result get_config() const { + return TRY_VM([this]() -> td::Result { + auto cs = vm::load_cell_slice(get_state().data); + Config config; + td::Ref dict_root; + auto ok = cs.advance(32 + 32 + 256) && cs.fetch_uint_to(32, config.start_at) && cs.fetch_maybe_ref(dict_root); + vm::Dictionary dict(std::move(dict_root), 32); + dict.check_for_each([&](auto cs, auto ptr, auto ptr_bits) { + auto r_seconds = td::narrow_cast_safe(dict.key_as_integer(ptr, true)->to_long()); + if (r_seconds.is_error()) { + ok = false; + return ok; + } + td::uint64 value; + ok &= smc::unpack_grams(cs, value); + config.limits.emplace_back(r_seconds.ok(), value); + return ok; + }); + if (!ok) { + return td::Status::Error("Can't parse config"); + } + std::sort(config.limits.begin(), config.limits.end()); + return config; + }()); + } + + static td::Ref get_init_data(const InitData& init_data) { + vm::CellBuilder cb; + cb.store_long(0, 32); + cb.store_long(init_data.wallet_id, 32); + CHECK(init_data.init_key.size() == 32); + CHECK(init_data.main_key.size() == 32); + cb.store_bytes(init_data.init_key.as_slice()); + cb.store_bytes(init_data.main_key.as_slice()); + return cb.finalize(); + } + + td::Result> get_init_message(const td::Ed25519::PrivateKey& init_private_key, + td::uint32 valid_until, const Config& config) const { + vm::CellBuilder cb; + TRY_RESULT(seqno, get_seqno()); + TRY_RESULT(wallet_id, get_wallet_id()); + LOG(ERROR) << "seqno: " << seqno << " wallet_id: " << wallet_id; + if (seqno != 0) { + return td::Status::Error("Wallet is already inited"); + } + + cb.store_long(wallet_id, 32); + cb.store_long(valid_until, 32); + cb.store_long(seqno, 32); + + cb.store_long(config.start_at, 32); + vm::Dictionary dict(32); + + auto add = [&](td::int32 till, td::uint64 value) { + auto key = dict.integer_key(td::make_refint(till), 32, true); + vm::CellBuilder gcb; + block::tlb::t_Grams.store_integer_value(gcb, td::BigInt256(value)); + dict.set_builder(key.bits(), 32, gcb); + }; + for (auto limit : config.limits) { + add(limit.first, limit.second); + } + cb.store_maybe_ref(dict.get_root_cell()); + + auto message_outer = cb.finalize(); + auto signature = init_private_key.sign(message_outer->get_hash().as_slice()).move_as_ok(); + return vm::CellBuilder().store_bytes(signature).append_cellslice(vm::load_cell_slice(message_outer)).finalize(); + } + + td::Result> make_a_gift_message(const td::Ed25519::PrivateKey& private_key, td::uint32 valid_until, + td::Span gifts) const override { + CHECK(gifts.size() <= Traits::max_gifts_size); + + vm::CellBuilder cb; + TRY_RESULT(seqno, get_seqno()); + TRY_RESULT(wallet_id, get_wallet_id()); + if (seqno == 0) { + return td::Status::Error("Wallet is not inited yet"); + } + cb.store_long(wallet_id, 32); + cb.store_long(valid_until, 32); + cb.store_long(seqno, 32); + + for (auto& gift : gifts) { + td::int32 send_mode = 3; + if (gift.gramms == -1) { + send_mode += 128; + } + cb.store_long(send_mode, 8).store_ref(create_int_message(gift)); + } + + auto message_outer = cb.finalize(); + auto signature = private_key.sign(message_outer->get_hash().as_slice()).move_as_ok(); + return vm::CellBuilder().store_bytes(signature).append_cellslice(vm::load_cell_slice(message_outer)).finalize(); + } +}; +} // namespace ton diff --git a/submodules/ton/tonlib-src/crypto/test/test-db.cpp b/submodules/ton/tonlib-src/crypto/test/test-db.cpp index f143ca0ac12..361c9947609 100644 --- a/submodules/ton/tonlib-src/crypto/test/test-db.cpp +++ b/submodules/ton/tonlib-src/crypto/test/test-db.cpp @@ -1542,6 +1542,7 @@ template class BenchBocDeserializer : public td::Benchmark { public: BenchBocDeserializer(std::string name, BenchBocDeserializerConfig config) : name_(std::move(name)), config_(config) { + td::PerfWarningTimer perf("A", 1); fast_array_ = vm::FastCompactArray(array_size); td::Random::Xorshift128plus rnd{123}; for (td::uint32 i = 0; i < array_size; i++) { diff --git a/submodules/ton/tonlib-src/crypto/test/test-smartcont.cpp b/submodules/ton/tonlib-src/crypto/test/test-smartcont.cpp index 5048bb28f62..ecd4b31ea9e 100644 --- a/submodules/ton/tonlib-src/crypto/test/test-smartcont.cpp +++ b/submodules/ton/tonlib-src/crypto/test/test-smartcont.cpp @@ -21,7 +21,9 @@ #include "Ed25519.h" +#include "block/block-auto.h" #include "block/block.h" +#include "block/block-parse.h" #include "fift/Fift.h" #include "fift/words.h" @@ -38,6 +40,7 @@ #include "smc-envelope/WalletV3.h" #include "smc-envelope/HighloadWallet.h" #include "smc-envelope/HighloadWalletV2.h" +#include "smc-envelope/PaymentChannel.h" #include "td/utils/base64.h" #include "td/utils/crypto.h" @@ -489,6 +492,99 @@ TEST(Tonlib, TestGiver) { CHECK(vm::std_boc_deserialize(wallet_query).move_as_ok()->get_hash() == res->get_hash()); } +TEST(Tonlib, RestrictedWallet) { + //auto source_lookup = fift::create_mem_source_lookup(load_source("smartcont/new-restricted-wallet2.fif")).move_as_ok(); + //source_lookup + //.write_file("/auto/restricted-wallet2-code.fif", load_source("smartcont/auto/restricted-wallet2-code.fif")) + //.ensure(); + //class ZeroOsTime : public fift::OsTime { + //public: + //td::uint32 now() override { + //return 0; + //} + //}; + //source_lookup.set_os_time(std::make_unique()); + //auto priv_key = td::Ed25519::generate_private_key().move_as_ok(); + //auto pub_key = priv_key.get_public_key().move_as_ok(); + //auto pub_key_serialized = block::PublicKey::from_bytes(pub_key.as_octet_string()).move_as_ok().serialize(true); + + //std::vector args = {"path", pub_key_serialized, std::string("100")}; + //auto fift_output = fift::mem_run_fift(std::move(source_lookup), args).move_as_ok(); + + //ton::RestrictedWallet::InitData init_data; + //td::uint64 x = 100 * 1000000000ull; + //init_data.key = &pub_key; + //init_data.start_at = 0; + //init_data.limits = {{-32768, x}, {92, x * 3 / 4}, {183, x * 1 / 2}, {366, x * 1 / 4}, {548, 0}}; + //auto wallet = ton::RestrictedWallet::create(init_data, -1); + + //ASSERT_EQ(0u, wallet->get_seqno().move_as_ok()); + //CHECK(pub_key.as_octet_string() == wallet->get_public_key().move_as_ok().as_octet_string()); + ////LOG(ERROR) << wallet->get_balance(x, 60 * 60 * 24 * 400).move_as_ok(); + + //auto new_wallet_query = fift_output.source_lookup.read_file("rwallet-query.boc").move_as_ok().data; + //auto new_wallet_addr = fift_output.source_lookup.read_file("rwallet.addr").move_as_ok().data; + + //auto address = wallet->get_address(-1); + ////CHECK(address.addr.as_slice() == td::Slice(new_wallet_addr).substr(0, 32)); + //address.bounceable = false; + //auto res = ton::GenericAccount::create_ext_message(address, wallet->get_init_state(), + //wallet->get_init_message(priv_key).move_as_ok()); + //LOG(ERROR) << "-------"; + //vm::load_cell_slice(res).print_rec(std::cerr); + //LOG(ERROR) << "-------"; + //vm::load_cell_slice(vm::std_boc_deserialize(new_wallet_query).move_as_ok()).print_rec(std::cerr); + //CHECK(vm::std_boc_deserialize(new_wallet_query).move_as_ok()->get_hash() == res->get_hash()); + + //auto dest = block::StdAddress::parse("Ef9Tj6fMJP+OqhAdhKXxq36DL+HYSzCc3+9O6UNzqsgPfYFX").move_as_ok(); + //fift_output.source_lookup.write_file("/main.fif", load_source("smartcont/wallet-v2.fif")).ensure(); + //fift_output.source_lookup.write_file("rwallet.pk", priv_key.as_octet_string().as_slice()).ensure(); + //fift_output = fift::mem_run_fift( + //std::move(fift_output.source_lookup), + //{"aba", "rwallet", "-C", "TESTv2", "Ef9Tj6fMJP+OqhAdhKXxq36DL+HYSzCc3+9O6UNzqsgPfYFX", "0", "321"}) + //.move_as_ok(); + //auto wallet_query = fift_output.source_lookup.read_file("wallet-query.boc").move_as_ok().data; + //ton::TestWallet::Gift gift; + //gift.destination = dest; + //gift.message = "TESTv2"; + //gift.gramms = 321000000000ll; + ////CHECK(priv_key.get_public_key().ok().as_octet_string() == wallet->get_public_key().ok().as_octet_string()); + //auto gift_message = ton::GenericAccount::create_ext_message( + //address, {}, wallet->make_a_gift_message(priv_key, 60, {gift}).move_as_ok()); + //LOG(ERROR) << "-------"; + //vm::load_cell_slice(gift_message).print_rec(std::cerr); + //LOG(ERROR) << "-------"; + //vm::load_cell_slice(vm::std_boc_deserialize(wallet_query).move_as_ok()).print_rec(std::cerr); + //CHECK(vm::std_boc_deserialize(wallet_query).move_as_ok()->get_hash() == gift_message->get_hash()); +} +TEST(Tonlib, RestrictedWallet3) { + auto init_priv_key = td::Ed25519::generate_private_key().move_as_ok(); + auto init_pub_key = init_priv_key.get_public_key().move_as_ok(); + auto priv_key = td::Ed25519::generate_private_key().move_as_ok(); + auto pub_key = priv_key.get_public_key().move_as_ok(); + + ton::RestrictedWallet::InitData init_data; + init_data.init_key = init_pub_key.as_octet_string(); + init_data.main_key = pub_key.as_octet_string(); + init_data.wallet_id = 123; + auto wallet = ton::RestrictedWallet::create(init_data, -1); + + auto address = wallet->get_address(); + + td::uint64 x = 100 * 1000000000ull; + ton::RestrictedWallet::Config config; + config.start_at = 1; + config.limits = {{-32768, x}, {92, x * 3 / 4}, {183, x * 1 / 2}, {366, x * 1 / 4}, {548, 0}}; + CHECK(wallet.write().send_external_message(wallet->get_init_message(init_priv_key, 10, config).move_as_ok()).success); + CHECK(wallet->get_seqno().move_as_ok() == 1); + + ton::WalletInterface::Gift gift; + gift.destination = address; + gift.message = "hello"; + CHECK(wallet.write().send_external_message(wallet->make_a_gift_message(priv_key, 10, {gift}).move_as_ok()).success); + CHECK(wallet->get_seqno().move_as_ok() == 2); +} + class SimpleWallet : public ton::SmartContract { public: SimpleWallet(State state) : SmartContract(std::move(state)) { @@ -1286,3 +1382,397 @@ TEST(Smartcont, DnsManual) { // TODO: rethink semantic of creating an empty dictionary do_dns_test(CheckedDns(true, true)); } + +using namespace ton::pchan; + +template +struct ValidateState { + T& self() { + return static_cast(*this); + } + + void init(td::Ref state) { + state_ = state; + block::gen::ChanData::Record data_rec; + if (!tlb::unpack_cell(state, data_rec)) { + on_fatal_error(td::Status::Error("Expected Data")); + return; + } + if (!tlb::unpack_cell(data_rec.state, self().rec)) { + on_fatal_error(td::Status::Error("Expected StatePayout")); + return; + } + CHECK(self().rec.A.not_null()); + } + + T& expect_grams(td::Ref cs, td::uint64 expected, td::Slice name) { + if (has_fatal_error_) { + return self(); + } + td::RefInt256 got; + CHECK(cs.not_null()); + CHECK(block::tlb::t_Grams.as_integer_to(cs, got)); + if (got->cmp(expected) != 0) { + on_error(td::Status::Error(PSLICE() << name << ": expected " << expected << ", got " << got->to_dec_string())); + } + return self(); + } + template + T& expect_eq(S a, S expected, td::Slice name) { + if (has_fatal_error_) { + return self(); + } + if (!(a == expected)) { + on_error(td::Status::Error(PSLICE() << name << ": expected " << expected << ", got " << a)); + } + return self(); + } + + td::Status finish() { + if (errors_.empty()) { + return td::Status::OK(); + } + std::stringstream ss; + block::gen::t_ChanData.print_ref(ss, state_); + td::StringBuilder sb; + for (auto& error : errors_) { + sb << error << "\n"; + } + sb << ss.str(); + return td::Status::Error(sb.as_cslice()); + } + + void on_fatal_error(td::Status error) { + CHECK(!has_fatal_error_); + has_fatal_error_ = true; + on_error(std::move(error)); + } + void on_error(td::Status error) { + CHECK(error.is_error()); + errors_.push_back(std::move(error)); + } + + public: + td::Ref state_; + bool has_fatal_error_{false}; + std::vector errors_; +}; + +struct ValidateStatePayout : public ValidateState { + ValidateStatePayout& expect_A(td::uint64 a) { + expect_grams(rec.A, a, "A"); + return *this; + } + ValidateStatePayout& expect_B(td::uint64 b) { + expect_grams(rec.B, b, "B"); + return *this; + } + + ValidateStatePayout(td::Ref state) { + init(std::move(state)); + } + + block::gen::ChanState::Record_chan_state_payout rec; +}; + +struct ValidateStateInit : public ValidateState { + ValidateStateInit& expect_A(td::uint64 a) { + expect_grams(rec.A, a, "A"); + return *this; + } + ValidateStateInit& expect_B(td::uint64 b) { + expect_grams(rec.B, b, "B"); + return *this; + } + ValidateStateInit& expect_min_A(td::uint64 a) { + expect_grams(rec.min_A, a, "min_A"); + return *this; + } + ValidateStateInit& expect_min_B(td::uint64 b) { + expect_grams(rec.min_B, b, "min_B"); + return *this; + } + ValidateStateInit& expect_expire_at(td::uint32 b) { + expect_eq(rec.expire_at, b, "expire_at"); + return *this; + } + ValidateStateInit& expect_signed_A(bool x) { + expect_eq(rec.signed_A, x, "signed_A"); + return *this; + } + ValidateStateInit& expect_signed_B(bool x) { + expect_eq(rec.signed_B, x, "signed_B"); + return *this; + } + + ValidateStateInit(td::Ref state) { + init(std::move(state)); + } + + block::gen::ChanState::Record_chan_state_init rec; +}; + +struct ValidateStateClose : public ValidateState { + ValidateStateClose& expect_A(td::uint64 a) { + expect_grams(rec.A, a, "A"); + return *this; + } + ValidateStateClose& expect_B(td::uint64 b) { + expect_grams(rec.B, b, "B"); + return *this; + } + ValidateStateClose& expect_promise_A(td::uint64 a) { + expect_grams(rec.promise_A, a, "promise_A"); + return *this; + } + ValidateStateClose& expect_promise_B(td::uint64 b) { + expect_grams(rec.promise_B, b, "promise_B"); + return *this; + } + ValidateStateClose& expect_expire_at(td::uint32 b) { + expect_eq(rec.expire_at, b, "expire_at"); + return *this; + } + ValidateStateClose& expect_signed_A(bool x) { + expect_eq(rec.signed_A, x, "signed_A"); + return *this; + } + ValidateStateClose& expect_signed_B(bool x) { + expect_eq(rec.signed_B, x, "signed_B"); + return *this; + } + + ValidateStateClose(td::Ref state) { + init(std::move(state)); + } + + block::gen::ChanState::Record_chan_state_close rec; +}; + +// config$_ initTimeout:int exitTimeout:int a_key:int256 b_key:int256 a_addr b_addr channel_id:int256 = Config; +TEST(Smarcont, Channel) { + auto code = ton::SmartContractCode::get_code(ton::SmartContractCode::PaymentChannel); + Config config; + auto a_pkey = td::Ed25519::generate_private_key().move_as_ok(); + auto b_pkey = td::Ed25519::generate_private_key().move_as_ok(); + config.init_timeout = 20; + config.close_timeout = 40; + auto dest = block::StdAddress::parse("Ef9Tj6fMJP+OqhAdhKXxq36DL+HYSzCc3+9O6UNzqsgPfYFX").move_as_ok(); + config.a_addr = dest; + config.b_addr = dest; + config.a_key = a_pkey.get_public_key().ok().as_octet_string(); + config.b_key = b_pkey.get_public_key().ok().as_octet_string(); + config.channel_id = 123; + + Data data; + data.config = config.serialize(); + data.state = data.init_state(); + auto data_cell = data.serialize(); + + auto channel = ton::SmartContract::create(ton::SmartContract::State{code, data_cell}); + ValidateStateInit(channel->get_state().data) + .expect_A(0) + .expect_B(0) + .expect_min_A(0) + .expect_min_B(0) + .expect_signed_A(false) + .expect_signed_B(false) + .expect_expire_at(0) + .finish() + .ensure(); + + enum err { + ok = 0, + wrong_a_signature = 31, + wrong_b_signature, + msg_value_too_small, + replay_protection, + no_timeout, + expected_init, + expected_close, + no_promise_signature, + wrong_channel_id + }; + +#define expect_code(description, expected_code, e) \ + { \ + auto res = e; \ + LOG_IF(FATAL, expected_code != res.code) << " res.code=" << res.code << " " << description << "\n" << #e; \ + } +#define expect_ok(description, e) expect_code(description, 0, e) + + expect_code("Trying to invoke a timeout while channel is empty", no_timeout, + channel.write().send_external_message(MsgTimeoutBuilder().finalize(), + ton::SmartContract::Args().set_now(1000000))); + + expect_code("External init message with no signatures", replay_protection, + channel.write().send_external_message(MsgInitBuilder().channel_id(config.channel_id).finalize())); + expect_code("Internal init message with not enough value", msg_value_too_small, + channel.write().send_internal_message( + MsgInitBuilder().channel_id(config.channel_id).inc_A(1000).min_B(2000).with_a_key(&a_pkey).finalize(), + ton::SmartContract::Args().set_amount(100))); + expect_code( + "Internal init message with wrong channel_id", wrong_channel_id, + channel.write().send_internal_message(MsgInitBuilder().inc_A(1000).min_B(2000).with_a_key(&a_pkey).finalize(), + ton::SmartContract::Args().set_amount(1000))); + expect_ok("A init with (inc_A = 1000, min_A = 1, min_B = 2000)", + channel.write().send_internal_message(MsgInitBuilder() + .channel_id(config.channel_id) + .inc_A(1000) + .min_A(1) + .min_B(2000) + .with_a_key(&a_pkey) + .finalize(), + ton::SmartContract::Args().set_amount(1000))); + ValidateStateInit(channel->get_state().data) + .expect_A(1000) + .expect_B(0) + .expect_min_A(1) + .expect_min_B(2000) + .expect_signed_A(true) + .expect_signed_B(false) + .expect_expire_at(config.init_timeout) + .finish() + .ensure(); + + expect_code("Repeated init of A init with (inc_A = 100, min_B = 5000). Must be ignored", replay_protection, + channel.write().send_internal_message( + MsgInitBuilder().channel_id(config.channel_id).inc_A(100).min_B(5000).with_a_key(&a_pkey).finalize(), + ton::SmartContract::Args().set_amount(1000))); + expect_code( + "Trying to invoke a timeout too early", no_timeout, + channel.write().send_external_message(MsgTimeoutBuilder().finalize(), ton::SmartContract::Args().set_now(0))); + + { + auto channel_copy = channel; + expect_ok("Invoke a timeout", channel_copy.write().send_external_message(MsgTimeoutBuilder().finalize(), + ton::SmartContract::Args().set_now(21))); + ValidateStatePayout(channel_copy->get_state().data).expect_A(1000).expect_B(0).finish().ensure(); + } + { + auto channel_copy = channel; + expect_ok("B init with inc_B < min_B. Leads to immediate payout", + channel_copy.write().send_internal_message( + MsgInitBuilder().channel_id(config.channel_id).inc_B(1500).with_b_key(&b_pkey).finalize(), + ton::SmartContract::Args().set_amount(1500))); + ValidateStatePayout(channel_copy->get_state().data).expect_A(1000).expect_B(1500).finish().ensure(); + } + + expect_ok("B init with (inc_B = 2000, min_A = 1, min_A = 1000)", + channel.write().send_internal_message( + MsgInitBuilder().channel_id(config.channel_id).inc_B(2000).min_A(1000).with_b_key(&b_pkey).finalize(), + ton::SmartContract::Args().set_amount(2000))); + ValidateStateClose(channel->get_state().data) + .expect_A(1000) + .expect_B(2000) + .expect_promise_A(0) + .expect_promise_B(0) + .expect_signed_A(false) + .expect_signed_B(false) + .expect_expire_at(0) + .finish() + .ensure(); + + { + auto channel_copy = channel; + expect_ok("A&B send Promise(1000000, 1000000 + 10) signed by nobody", + channel_copy.write().send_external_message(MsgCloseBuilder() + .signed_promise(SignedPromiseBuilder() + .promise_A(1000000) + .promise_B(1000000 + 10) + .channel_id(config.channel_id) + .finalize()) + .with_a_key(&a_pkey) + .with_b_key(&b_pkey) + .finalize(), + ton::SmartContract::Args().set_now(21))); + ValidateStatePayout(channel_copy->get_state().data).expect_A(1000 + 10).expect_B(2000 - 10).finish().ensure(); + } + { + auto channel_copy = channel; + expect_ok("A&B send Promise(1000000, 1000000 + 10) signed by A", + channel_copy.write().send_external_message(MsgCloseBuilder() + .signed_promise(SignedPromiseBuilder() + .promise_A(1000000) + .promise_B(1000000 + 10) + .with_key(&a_pkey) + .channel_id(config.channel_id) + .finalize()) + .with_a_key(&a_pkey) + .with_b_key(&b_pkey) + .finalize(), + ton::SmartContract::Args().set_now(21))); + ValidateStatePayout(channel_copy->get_state().data).expect_A(1000 + 10).expect_B(2000 - 10).finish().ensure(); + } + + expect_code( + "A sends Promise(1000000, 0) signed by A", wrong_b_signature, + channel.write().send_external_message( + MsgCloseBuilder() + .signed_promise( + SignedPromiseBuilder().promise_A(1000000).with_key(&a_pkey).channel_id(config.channel_id).finalize()) + .with_a_key(&a_pkey) + .finalize(), + ton::SmartContract::Args().set_now(21))); + expect_code( + "B sends Promise(1000000, 0) signed by B", wrong_a_signature, + channel.write().send_external_message( + MsgCloseBuilder() + .signed_promise( + SignedPromiseBuilder().promise_A(1000000).with_key(&b_pkey).channel_id(config.channel_id).finalize()) + .with_b_key(&b_pkey) + .finalize(), + ton::SmartContract::Args().set_now(21))); + expect_code("B sends Promise(1000000, 0) signed by A with wrong channel_id", wrong_channel_id, + channel.write().send_external_message(MsgCloseBuilder() + .signed_promise(SignedPromiseBuilder() + .promise_A(1000000) + .with_key(&a_pkey) + .channel_id(config.channel_id + 1) + .finalize()) + .with_b_key(&b_pkey) + .finalize(), + ton::SmartContract::Args().set_now(21))); + expect_code( + "B sends unsigned Promise(1000000, 0)", no_promise_signature, + channel.write().send_external_message( + MsgCloseBuilder() + .signed_promise(SignedPromiseBuilder().promise_A(1000000).channel_id(config.channel_id).finalize()) + .with_b_key(&b_pkey) + .finalize(), + ton::SmartContract::Args().set_now(21))); + + expect_ok( + "B sends Promise(1000000, 0) signed by A", + channel.write().send_external_message( + MsgCloseBuilder() + .signed_promise( + SignedPromiseBuilder().promise_A(1000000).with_key(&a_pkey).channel_id(config.channel_id).finalize()) + .with_b_key(&b_pkey) + .finalize(), + ton::SmartContract::Args().set_now(21))); + ValidateStateClose(channel->get_state().data) + .expect_A(1000) + .expect_B(2000) + .expect_promise_A(1000000) + .expect_promise_B(0) + .expect_signed_A(false) + .expect_signed_B(true) + .expect_expire_at(21 + config.close_timeout) + .finish() + .ensure(); + + expect_ok("B sends Promise(0, 1000000 + 10) signed by A", + channel.write().send_external_message(MsgCloseBuilder() + .signed_promise(SignedPromiseBuilder() + .promise_B(1000000 + 10) + .with_key(&b_pkey) + .channel_id(config.channel_id) + .finalize()) + .with_a_key(&a_pkey) + .finalize(), + ton::SmartContract::Args().set_now(21))); + ValidateStatePayout(channel->get_state().data).expect_A(1000 + 10).expect_B(2000 - 10).finish().ensure(); +#undef expect_ok +#undef expect_code +} diff --git a/submodules/ton/tonlib-src/crypto/vm/cells/CellSlice.cpp b/submodules/ton/tonlib-src/crypto/vm/cells/CellSlice.cpp index 0d539c74e63..916fc0238d4 100644 --- a/submodules/ton/tonlib-src/crypto/vm/cells/CellSlice.cpp +++ b/submodules/ton/tonlib-src/crypto/vm/cells/CellSlice.cpp @@ -19,6 +19,7 @@ #include "vm/cells/CellSlice.h" #include "vm/excno.hpp" #include "td/utils/bits.h" +#include "td/utils/misc.h" namespace vm { @@ -719,6 +720,10 @@ bool CellSlice::prefetch_bytes(unsigned char* buffer, unsigned bytes) const { } } +bool CellSlice::fetch_bytes(td::MutableSlice slice) { + return fetch_bytes(slice.ubegin(), td::narrow_cast(slice.size())); +} + bool CellSlice::fetch_bytes(unsigned char* buffer, unsigned bytes) { if (prefetch_bytes(buffer, bytes)) { advance(bytes * 8); @@ -728,6 +733,10 @@ bool CellSlice::fetch_bytes(unsigned char* buffer, unsigned bytes) { } } +bool CellSlice::prefetch_bytes(td::MutableSlice slice) const { + return prefetch_bytes(slice.ubegin(), td::narrow_cast(slice.size())); +} + Ref CellSlice::prefetch_ref(unsigned offset) const { if (offset < size_refs()) { auto ref_id = refs_st + offset; diff --git a/submodules/ton/tonlib-src/crypto/vm/cells/CellSlice.h b/submodules/ton/tonlib-src/crypto/vm/cells/CellSlice.h index a2e528d685d..33fad7410fe 100644 --- a/submodules/ton/tonlib-src/crypto/vm/cells/CellSlice.h +++ b/submodules/ton/tonlib-src/crypto/vm/cells/CellSlice.h @@ -218,7 +218,9 @@ class CellSlice : public td::CntObject { return prefetch_bits_to(buffer.bits(), n); } bool fetch_bytes(unsigned char* buffer, unsigned bytes); + bool fetch_bytes(td::MutableSlice slice); bool prefetch_bytes(unsigned char* buffer, unsigned bytes) const; + bool prefetch_bytes(td::MutableSlice slice) const; td::BitSlice as_bitslice() const { return prefetch_bits(size()); } diff --git a/submodules/ton/tonlib-src/crypto/vm/cells/MerkleProof.cpp b/submodules/ton/tonlib-src/crypto/vm/cells/MerkleProof.cpp index a1c4131fc3d..aee3436749f 100644 --- a/submodules/ton/tonlib-src/crypto/vm/cells/MerkleProof.cpp +++ b/submodules/ton/tonlib-src/crypto/vm/cells/MerkleProof.cpp @@ -148,6 +148,11 @@ class MerkleProofCombineFast { MerkleProofCombineFast(Ref a, Ref b) : a_(std::move(a)), b_(std::move(b)) { } td::Result> run() { + if (a_.is_null()) { + return b_; + } else if (b_.is_null()) { + return a_; + } TRY_RESULT_ASSIGN(a_, unpack_proof(a_)); TRY_RESULT_ASSIGN(b_, unpack_proof(b_)); TRY_RESULT(res, run_raw()); @@ -204,6 +209,11 @@ class MerkleProofCombine { MerkleProofCombine(Ref a, Ref b) : a_(std::move(a)), b_(std::move(b)) { } td::Result> run() { + if (a_.is_null()) { + return b_; + } else if (b_.is_null()) { + return a_; + } TRY_RESULT_ASSIGN(a_, unpack_proof(a_)); TRY_RESULT_ASSIGN(b_, unpack_proof(b_)); TRY_RESULT(res, run_raw()); @@ -323,6 +333,10 @@ Ref MerkleProof::combine(Ref a, Ref b) { return res.move_as_ok(); } +td::Result> MerkleProof::combine_status(Ref a, Ref b) { + return MerkleProofCombine(std::move(a), std::move(b)).run(); +} + Ref MerkleProof::combine_fast(Ref a, Ref b) { auto res = MerkleProofCombineFast(std::move(a), std::move(b)).run(); if (res.is_error()) { @@ -331,6 +345,10 @@ Ref MerkleProof::combine_fast(Ref a, Ref b) { return res.move_as_ok(); } +td::Result> MerkleProof::combine_fast_status(Ref a, Ref b) { + return MerkleProofCombineFast(std::move(a), std::move(b)).run(); +} + Ref MerkleProof::combine_raw(Ref a, Ref b) { auto res = MerkleProofCombine(std::move(a), std::move(b)).run_raw(); if (res.is_error()) { diff --git a/submodules/ton/tonlib-src/crypto/vm/cells/MerkleProof.h b/submodules/ton/tonlib-src/crypto/vm/cells/MerkleProof.h index cb50f1d093d..4f2add6c4eb 100644 --- a/submodules/ton/tonlib-src/crypto/vm/cells/MerkleProof.h +++ b/submodules/ton/tonlib-src/crypto/vm/cells/MerkleProof.h @@ -38,7 +38,9 @@ class MerkleProof { static Ref virtualize(Ref cell, int virtualization); static Ref combine(Ref a, Ref b); + static td::Result> combine_status(Ref a, Ref b); static Ref combine_fast(Ref a, Ref b); + static td::Result> combine_fast_status(Ref a, Ref b); // works with upwrapped proofs // works fine with cell of non-zero level, but this is not supported (yet?) in MerkeProof special cell diff --git a/submodules/ton/tonlib-src/crypto/vm/db/TonDb.cpp b/submodules/ton/tonlib-src/crypto/vm/db/TonDb.cpp index 68f677a1e1d..ac69973fd03 100644 --- a/submodules/ton/tonlib-src/crypto/vm/db/TonDb.cpp +++ b/submodules/ton/tonlib-src/crypto/vm/db/TonDb.cpp @@ -255,15 +255,15 @@ TonDbTransactionImpl::TonDbTransactionImpl(std::shared_ptr kv) : kv_(s } void TonDbTransactionImpl::begin() { - kv_->begin_transaction(); + kv_->begin_write_batch(); generation_++; } void TonDbTransactionImpl::commit() { - kv_->commit_transaction(); + kv_->commit_write_batch(); reader_.reset(kv_->snapshot().release()); } void TonDbTransactionImpl::abort() { - kv_->abort_transaction(); + kv_->abort_write_batch(); } void TonDbTransactionImpl::clear_cache() { contracts_ = {}; diff --git a/submodules/ton/tonlib-src/crypto/vm/excno.hpp b/submodules/ton/tonlib-src/crypto/vm/excno.hpp index 31742e08353..3be481683bf 100644 --- a/submodules/ton/tonlib-src/crypto/vm/excno.hpp +++ b/submodules/ton/tonlib-src/crypto/vm/excno.hpp @@ -77,6 +77,13 @@ class VmError { long long get_arg() const { return arg; } + td::Status as_status() const { + return td::Status::Error(td::Slice{get_msg()}); + } + template + td::Status as_status(T pfx) const { + return td::Status::Error(PSLICE() << pfx << get_msg()); + } }; struct VmNoGas { @@ -90,6 +97,13 @@ struct VmNoGas { operator VmError() const { return VmError{Excno::out_of_gas, "out of gas"}; } + td::Status as_status() const { + return td::Status::Error(td::Slice{get_msg()}); + } + template + td::Status as_status(T pfx) const { + return td::Status::Error(PSLICE() << pfx << get_msg()); + } }; struct VmVirtError { @@ -106,6 +120,13 @@ struct VmVirtError { operator VmError() const { return VmError{Excno::virt_err, "prunned branch", virtualization}; } + td::Status as_status() const { + return td::Status::Error(td::Slice{get_msg()}); + } + template + td::Status as_status(T pfx) const { + return td::Status::Error(PSLICE() << pfx << get_msg()); + } }; struct VmFatal {}; @@ -114,12 +135,12 @@ template auto try_f(F&& f) noexcept -> decltype(f()) { try { return f(); - } catch (vm::VmError error) { - return td::Status::Error(PSLICE() << "Got a vm exception: " << error.get_msg()); - } catch (vm::VmVirtError error) { - return td::Status::Error(PSLICE() << "Got a vm virtualization exception: " << error.get_msg()); - } catch (vm::VmNoGas error) { - return td::Status::Error(PSLICE() << "Got a vm no gas exception: " << error.get_msg()); + } catch (vm::VmError& error) { + return error.as_status("Got a vm exception: "); + } catch (vm::VmVirtError& error) { + return error.as_status("Got a vm virtualization exception: "); + } catch (vm::VmNoGas& error) { + return error.as_status("Got a vm no gas exception: "); } } diff --git a/submodules/ton/tonlib-src/lite-client/lite-client.cpp b/submodules/ton/tonlib-src/lite-client/lite-client.cpp index f1f90f4271c..a60003e5ebc 100644 --- a/submodules/ton/tonlib-src/lite-client/lite-client.cpp +++ b/submodules/ton/tonlib-src/lite-client/lite-client.cpp @@ -135,8 +135,36 @@ void TestNode::run() { ton::adnl::AdnlExtClient::create(ton::adnl::AdnlNodeIdFull{remote_public_key_}, remote_addr_, make_callback()); } -void TestNode::got_result() { +void TestNode::got_result(td::Result R, td::Promise promise) { + if (R.is_error()) { + auto err = R.move_as_error(); + LOG(ERROR) << "failed query: " << err; + promise.set_error(std::move(err)); + td::actor::send_closure_later(actor_id(this), &TestNode::after_got_result, false); + return; + } + auto data = R.move_as_ok(); + auto F = ton::fetch_tl_object(data.clone(), true); + if (F.is_ok()) { + auto f = F.move_as_ok(); + auto err = td::Status::Error(f->code_, f->message_); + LOG(ERROR) << "liteserver error: " << err; + promise.set_error(std::move(err)); + td::actor::send_closure_later(actor_id(this), &TestNode::after_got_result, false); + return; + } + promise.set_result(std::move(data)); + td::actor::send_closure_later(actor_id(this), &TestNode::after_got_result, true); +} + +void TestNode::after_got_result(bool ok) { running_queries_--; + if (ex_mode_ && !ok) { + LOG(ERROR) << "fatal error executing command-line queries, skipping the rest"; + std::cout.flush(); + std::cerr.flush(); + std::_Exit(1); + } if (!running_queries_ && ex_queries_.size() > 0) { auto data = std::move(ex_queries_[0]); ex_queries_.erase(ex_queries_.begin()); @@ -152,28 +180,12 @@ void TestNode::got_result() { bool TestNode::envelope_send_query(td::BufferSlice query, td::Promise promise) { running_queries_++; if (!ready_ || client_.empty()) { - LOG(ERROR) << "failed to send query to server: not ready"; + got_result(td::Status::Error("failed to send query to server: not ready"), std::move(promise)); return false; } auto P = td::PromiseCreator::lambda( [SelfId = actor_id(this), promise = std::move(promise)](td::Result R) mutable { - if (R.is_error()) { - auto err = R.move_as_error(); - LOG(ERROR) << "failed query: " << err; - promise.set_error(std::move(err)); - return; - } - auto data = R.move_as_ok(); - auto F = ton::fetch_tl_object(data.clone(), true); - if (F.is_ok()) { - auto f = F.move_as_ok(); - auto err = td::Status::Error(f->code_, f->message_); - LOG(ERROR) << "received error: " << err; - promise.set_error(std::move(err)); - return; - } - promise.set_result(std::move(data)); - td::actor::send_closure(SelfId, &TestNode::got_result); + td::actor::send_closure(SelfId, &TestNode::got_result, std::move(R), std::move(promise)); }); td::BufferSlice b = ton::serialize_tl_object(ton::create_tl_object(std::move(query)), true); @@ -306,7 +318,7 @@ bool TestNode::get_server_time() { LOG(ERROR) << "cannot parse answer to liteServer.getTime"; } else { server_time_ = F.move_as_ok()->now_; - server_time_got_at_ = static_cast(td::Clocks::system()); + server_time_got_at_ = now(); LOG(INFO) << "server time is " << server_time_ << " (delta " << server_time_ - server_time_got_at_ << ")"; } } @@ -355,7 +367,7 @@ void TestNode::set_server_version(td::int32 version, td::int64 capabilities) { void TestNode::set_server_time(int server_utime) { server_time_ = server_utime; - server_time_got_at_ = static_cast(td::Clocks::system()); + server_time_got_at_ = now(); LOG(INFO) << "server time is " << server_time_ << " (delta " << server_time_ - server_time_got_at_ << ")"; } @@ -425,8 +437,7 @@ void TestNode::got_server_mc_block_id(ton::BlockIdExt blkid, ton::ZeroStateIdExt } td::TerminalIO::out() << "latest masterchain block known to server is " << blkid.to_str(); if (created > 0) { - td::TerminalIO::out() << " created at " << created << " (" << static_cast(td::Clocks::system()) - created - << " seconds ago)\n"; + td::TerminalIO::out() << " created at " << created << " (" << now() - created << " seconds ago)\n"; } else { td::TerminalIO::out() << "\n"; } @@ -898,6 +909,8 @@ bool TestNode::show_help(std::string command) { "getconfig [...]\tShows specified or all configuration parameters from the latest masterchain state\n" "getconfigfrom [...]\tShows specified or all configuration parameters from the " "masterchain state of \n" + "getkeyconfig [...]\tShows specified or all configuration parameters from the " + "previous key block with respect to \n" "saveconfig []\tSaves all configuration parameters into specified file\n" "gethead \tShows block header for \n" "getblock \tDownloads block\n" @@ -924,6 +937,10 @@ bool TestNode::show_help(std::string command) { "recentcreatorstats [ []]\tLists block creator statistics " "updated after by validator public " "key\n" + "checkload[all|severe] []\tChecks whether all validators worked " + "properly during specified time " + "interval, and optionally saves proofs into -.boc\n" + "loadproofcheck \tChecks a validator misbehavior proof previously created by checkload\n" "known\tShows the list of all known block ids\n" "knowncells\tShows the list of hashes of all known (cached) cells\n" "dumpcell \nDumps a cached cell by a prefix of its hash\n" @@ -989,10 +1006,12 @@ bool TestNode::do_parse_line() { blkid = mc_last_id_; std::string filename; return get_word_to(filename) && (seekeoln() || parse_block_id_ext(blkid)) && seekeoln() && - get_config_params(blkid, trivial_promise(), -1, filename); + parse_get_config_params(blkid, -1, filename); } else if (word == "getconfig" || word == "getconfigfrom") { blkid = mc_last_id_; - return (word == "getconfig" || parse_block_id_ext(blkid)) && get_config_params(blkid, trivial_promise(), 0); + return (word == "getconfig" || parse_block_id_ext(blkid)) && parse_get_config_params(blkid, 0); + } else if (word == "getkeyconfig") { + return parse_block_id_ext(blkid) && parse_get_config_params(blkid, 0x8000); } else if (word == "getblock") { return parse_block_id_ext(blkid) && seekeoln() && get_block(blkid, false); } else if (word == "dumpblock") { @@ -1002,7 +1021,7 @@ bool TestNode::do_parse_line() { } else if (word == "dumpstate") { return parse_block_id_ext(blkid) && seekeoln() && get_state(blkid, true); } else if (word == "gethead") { - return parse_block_id_ext(blkid) && seekeoln() && get_block_header(blkid, 0xffff); + return parse_block_id_ext(blkid) && seekeoln() && get_show_block_header(blkid, 0xffff); } else if (word == "dumptrans") { return parse_block_id_ext(blkid) && parse_account_addr(workchain, addr) && parse_lt(lt) && seekeoln() && get_one_transaction(blkid, workchain, addr, lt, true); @@ -1022,17 +1041,25 @@ bool TestNode::do_parse_line() { return parse_block_id_ext(blkid) && (seekeoln() || parse_block_id_ext(blkid2)) && seekeoln() && get_block_proof(blkid, blkid2, blkid2.is_valid() + (word == "blkproofchain") * 0x1000); } else if (word == "byseqno") { - return parse_shard_id(shard) && parse_uint32(seqno) && seekeoln() && lookup_block(shard, 1, seqno); + return parse_shard_id(shard) && parse_uint32(seqno) && seekeoln() && lookup_show_block(shard, 1, seqno); } else if (word == "byutime") { - return parse_shard_id(shard) && parse_uint32(utime) && seekeoln() && lookup_block(shard, 4, utime); + return parse_shard_id(shard) && parse_uint32(utime) && seekeoln() && lookup_show_block(shard, 4, utime); } else if (word == "bylt") { - return parse_shard_id(shard) && parse_lt(lt) && seekeoln() && lookup_block(shard, 2, lt); + return parse_shard_id(shard) && parse_lt(lt) && seekeoln() && lookup_show_block(shard, 2, lt); } else if (word == "creatorstats" || word == "recentcreatorstats") { count = 1000; int mode = (word == "recentcreatorstats" ? 4 : 0); - return parse_block_id_ext(blkid) && (!mode || parse_uint32(utime)) && (seekeoln() || parse_uint32(count)) && - (seekeoln() || (parse_hash(hash) && (mode |= 1))) && seekeoln() && - get_creator_stats(blkid, mode, count, hash, utime); + return parse_block_id_ext(blkid) && (!mode || parse_uint32(utime)) && + (seekeoln() ? (mode |= 0x100) : parse_uint32(count)) && (seekeoln() || (parse_hash(hash) && (mode |= 1))) && + seekeoln() && get_creator_stats(blkid, mode, count, hash, utime); + } else if (word == "checkload" || word == "checkloadall" || word == "checkloadsevere") { + int time1, time2, mode = (word == "checkloadsevere"); + std::string file_pfx; + return parse_int32(time1) && parse_int32(time2) && (seekeoln() || ((mode |= 2) && get_word_to(file_pfx))) && + seekeoln() && check_validator_load(time1, time2, mode, file_pfx); + } else if (word == "loadproofcheck") { + std::string filename; + return get_word_to(filename) && seekeoln() && set_error(check_validator_load_proof(filename)); } else if (word == "known") { return eoln() && show_new_blkids(true); } else if (word == "knowncells") { @@ -1293,16 +1320,17 @@ bool TestNode::dns_resolve_start(ton::WorkchainId workchain, ton::StdSmcAddress workchain = ton::masterchainId; addr = dns_root_; } else { - auto P = td::PromiseCreator::lambda([this, blkid, domain, cat, mode](td::Result R) { - if (R.is_error()) { - LOG(ERROR) << "cannot obtain root dns address from configuration: " << R.move_as_error(); - } else if (dns_root_queried_) { - dns_resolve_start(ton::masterchainId, dns_root_, blkid, domain, cat, mode); - } else { - LOG(ERROR) << "cannot obtain root dns address from configuration parameter #4"; - } - }); - return get_config_params(mc_last_id_, std::move(P), 0x5000, "", {4}); + auto P = + td::PromiseCreator::lambda([this, blkid, domain, cat, mode](td::Result> R) { + if (R.is_error()) { + LOG(ERROR) << "cannot obtain root dns address from configuration: " << R.move_as_error(); + } else if (dns_root_queried_) { + dns_resolve_start(ton::masterchainId, dns_root_, blkid, domain, cat, mode); + } else { + LOG(ERROR) << "cannot obtain root dns address from configuration parameter #4"; + } + }); + return get_config_params(mc_last_id_, std::move(P), 0x3000, "", {4}); } } return dns_resolve_send(workchain, addr, blkid, domain, qdomain, cat, mode); @@ -2185,107 +2213,138 @@ void TestNode::got_all_shards(ton::BlockIdExt blk, td::BufferSlice proof, td::Bu show_new_blkids(); } -bool TestNode::get_config_params(ton::BlockIdExt blkid, td::Promise do_after, int mode, std::string filename, - std::vector params) { +bool TestNode::parse_get_config_params(ton::BlockIdExt blkid, int mode, std::string filename, std::vector params) { if (mode < 0) { - mode = 0x8000; + mode = 0x80000; } - if (!(mode & 0x9000) && !seekeoln()) { + if (!(mode & 0x81000) && !seekeoln()) { mode |= 0x1000; while (!seekeoln()) { int x; if (!convert_int32(get_word(), x)) { - do_after.set_error(td::Status::Error("integer configuration parameter id expected")); return set_error("integer configuration parameter id expected"); } params.push_back(x); } } if (!(ready_ && !client_.empty())) { - do_after.set_error(td::Status::Error("integer configuration parameter id expected")); return set_error("server connection not ready"); } if (!blkid.is_masterchain_ext()) { - do_after.set_error(td::Status::Error("integer configuration parameter id expected")); return set_error("only masterchain blocks contain configuration"); } if (blkid == mc_last_id_) { mode |= 0x2000; } + return get_config_params(blkid, trivial_promise_of>(), mode, filename, + std::move(params)); +} + +bool TestNode::get_config_params(ton::BlockIdExt blkid, td::Promise> promise, int mode, + std::string filename, std::vector params) { + return get_config_params_ext(blkid, promise.wrap([](ConfigInfo&& info) { return std::move(info.config); }), + mode | 0x10000, filename, params); +} + +bool TestNode::get_config_params_ext(ton::BlockIdExt blkid, td::Promise promise, int mode, + std::string filename, std::vector params) { + if (!(ready_ && !client_.empty())) { + promise.set_error(td::Status::Error("server connection not ready")); + return false; + } + if (!blkid.is_masterchain_ext()) { + promise.set_error(td::Status::Error("masterchain reference block expected")); + return false; + } + if (blkid == mc_last_id_) { + mode |= 0x2000; + } auto params_copy = params; - auto b = (mode & 0x1000) - ? ton::serialize_tl_object(ton::create_tl_object( - 0, ton::create_tl_lite_block_id(blkid), std::move(params_copy)), - true) - : ton::serialize_tl_object(ton::create_tl_object( - 0, ton::create_tl_lite_block_id(blkid)), - true); + auto b = (mode & 0x1000) ? ton::serialize_tl_object( + ton::create_tl_object( + mode & 0x8fff, ton::create_tl_lite_block_id(blkid), std::move(params_copy)), + true) + : ton::serialize_tl_object(ton::create_tl_object( + mode & 0x8fff, ton::create_tl_lite_block_id(blkid)), + true); LOG(INFO) << "requesting " << params.size() << " configuration parameters with respect to masterchain block " << blkid.to_str(); return envelope_send_query(std::move(b), [Self = actor_id(this), mode, filename, blkid, params = std::move(params), - do_after = std::move(do_after)](td::Result R) mutable { - if (R.is_error()) { - do_after.set_error(R.move_as_error()); - return; - } - auto F = ton::fetch_tl_object(R.move_as_ok(), true); - if (F.is_error()) { - LOG(ERROR) << "cannot parse answer to liteServer.getConfigParams"; - } else { - auto f = F.move_as_ok(); - td::actor::send_closure_later(Self, &TestNode::got_config_params, blkid, ton::create_block_id(f->id_), - std::move(f->state_proof_), std::move(f->config_proof_), mode, filename, - std::move(params), std::move(do_after)); - } + promise = std::move(promise)](td::Result R) mutable { + td::actor::send_closure_later(Self, &TestNode::got_config_params, blkid, mode, filename, std::move(params), + std::move(R), std::move(promise)); }); } -void TestNode::got_config_params(ton::BlockIdExt req_blkid, ton::BlockIdExt blkid, td::BufferSlice state_proof, - td::BufferSlice cfg_proof, int mode, std::string filename, std::vector params, - td::Promise do_after) { +void TestNode::got_config_params(ton::BlockIdExt req_blkid, int mode, std::string filename, std::vector params, + td::Result R, td::Promise promise) { + TRY_RESULT_PROMISE(promise, res, std::move(R)); + TRY_RESULT_PROMISE_PREFIX(promise, f, + ton::fetch_tl_object(std::move(res), true), + "cannot parse answer to liteServer.getConfigParams"); + auto blkid = ton::create_block_id(f->id_); LOG(INFO) << "got configuration parameters"; if (!blkid.is_masterchain_ext()) { - LOG(ERROR) << "reference block " << blkid.to_str() << " for the configuration is not a valid masterchain block"; + promise.set_error(td::Status::Error("reference block "s + blkid.to_str() + + " for the configuration is not a valid masterchain block")); return; } - if (blkid != req_blkid) { - LOG(ERROR) << "got configuration parameters with respect to block " << blkid.to_str() << " instead of " - << req_blkid.to_str(); - return; - } - auto R = block::check_extract_state_proof(blkid, state_proof.as_slice(), cfg_proof.as_slice()); - if (R.is_error()) { - LOG(ERROR) << "masterchain state proof for " << blkid.to_str() << " is invalid : " << R.move_as_error().to_string(); + bool from_key = (mode & 0x8000); + if (blkid.seqno() > req_blkid.seqno() || (!from_key && blkid != req_blkid)) { + promise.set_error(td::Status::Error("got configuration parameters with respect to block "s + blkid.to_str() + + " instead of " + req_blkid.to_str())); return; } try { - auto res = block::Config::extract_from_state(R.move_as_ok(), mode >= 0 ? mode & 0xfff : 0); - if (res.is_error()) { - LOG(ERROR) << "cannot unpack configuration: " << res.move_as_error().to_string(); - return; - } - auto config = res.move_as_ok(); - if (mode & 0x8000) { - auto F = vm::std_boc_serialize(config->get_root_cell(), 2); - if (F.is_error()) { - LOG(ERROR) << "cannot serialize configuration: " << F.move_as_error().to_string(); - return; - } - auto size = F.ok().size(); - auto W = td::write_file(filename, F.move_as_ok()); - if (W.is_error()) { - LOG(ERROR) << "cannot save file `" << filename << "` : " << W.move_as_error().to_string(); + Ref state, block, state_proof, config_proof; + if (!(mode & 0x10000) && !from_key) { + TRY_RESULT_PROMISE_PREFIX_ASSIGN(promise, state_proof, vm::std_boc_deserialize(f->state_proof_.as_slice()), + "cannot deserialize state proof :"); + } + if (!(mode & 0x10000) || from_key) { + TRY_RESULT_PROMISE_PREFIX_ASSIGN(promise, config_proof, vm::std_boc_deserialize(f->config_proof_.as_slice()), + "cannot deserialize config proof :"); + } + if (!from_key) { + TRY_RESULT_PROMISE_PREFIX_ASSIGN( + promise, state, + block::check_extract_state_proof(blkid, f->state_proof_.as_slice(), f->config_proof_.as_slice()), + PSLICE() << "masterchain state proof for " << blkid.to_str() << " is invalid :"); + } else { + block = vm::MerkleProof::virtualize(config_proof, 1); + if (block.is_null()) { + promise.set_error( + td::Status::Error("cannot virtualize configuration proof constructed from key block "s + blkid.to_str())); return; } + TRY_STATUS_PROMISE_PREFIX(promise, block::check_block_header_proof(config_proof, blkid), + PSLICE() << "incorrect header for key block " << blkid.to_str()); + } + TRY_RESULT_PROMISE_PREFIX(promise, config, + from_key ? block::Config::extract_from_key_block(block, mode & 0xfff) + : block::Config::extract_from_state(state, mode & 0xfff), + "cannot unpack configuration:"); + ConfigInfo cinfo{std::move(config), std::move(state_proof), std::move(config_proof)}; + if (mode & 0x80000) { + TRY_RESULT_PROMISE_PREFIX(promise, boc, vm::std_boc_serialize(cinfo.config->get_root_cell(), 2), + "cannot serialize configuration:"); + auto size = boc.size(); + TRY_STATUS_PROMISE_PREFIX(promise, td::write_file(filename, std::move(boc)), + PSLICE() << "cannot save file `" << filename << "` :"); td::TerminalIO::out() << "saved configuration dictionary into file `" << filename << "` (" << size << " bytes written)" << std::endl; + promise.set_result(std::move(cinfo)); + return; + } + if (mode & 0x4000) { + promise.set_result(std::move(cinfo)); return; } auto out = td::TerminalIO::out(); if (mode & 0x1000) { for (int i : params) { out << "ConfigParam(" << i << ") = "; - auto value = config->get_config_param(i); + auto value = cinfo.config->get_config_param(i); if (value.is_null()) { out << "(null)\n"; } else { @@ -2302,7 +2361,7 @@ void TestNode::got_config_params(ton::BlockIdExt req_blkid, ton::BlockIdExt blki } } } else { - config->foreach_config_param([this, &out, mode](int i, Ref value) { + cinfo.config->foreach_config_param([this, &out, mode](int i, Ref value) { out << "ConfigParam(" << i << ") = "; if (value.is_null()) { out << "(null)\n"; @@ -2321,12 +2380,14 @@ void TestNode::got_config_params(ton::BlockIdExt req_blkid, ton::BlockIdExt blki return true; }); } + promise.set_result(std::move(cinfo)); } catch (vm::VmError& err) { - LOG(ERROR) << "error while traversing configuration: " << err.get_msg(); + promise.set_error(err.as_status("error while traversing configuration: ")); + return; } catch (vm::VmVirtError& err) { - LOG(ERROR) << "virtualization error while traversing configuration: " << err.get_msg(); + promise.set_error(err.as_status("virtualization error while traversing configuration: ")); + return; } - do_after.set_result(td::Unit()); } bool TestNode::register_config_param4(Ref value) { @@ -2517,61 +2578,97 @@ void TestNode::got_state(ton::BlockIdExt blkid, ton::RootHash root_hash, ton::Fi show_new_blkids(); } -bool TestNode::get_block_header(ton::BlockIdExt blkid, int mode) { +bool TestNode::get_show_block_header(ton::BlockIdExt blkid, int mode) { + return get_block_header(blkid, mode, [this, blkid](td::Result R) { + if (R.is_error()) { + LOG(ERROR) << "unable to fetch block header: " << R.move_as_error(); + } else { + auto res = R.move_as_ok(); + show_block_header(res.blk_id, res.virt_blk_root, res.mode); + show_new_blkids(); + } + }); +} + +bool TestNode::get_block_header(ton::BlockIdExt blkid, int mode, td::Promise promise) { LOG(INFO) << "got block header request for " << blkid.to_str() << " with mode " << mode; auto b = ton::serialize_tl_object( ton::create_tl_object(ton::create_tl_lite_block_id(blkid), mode), true); - return envelope_send_query(std::move(b), [Self = actor_id(this), blkid](td::Result res) -> void { - if (res.is_error()) { - LOG(ERROR) << "cannot obtain block header for " << blkid.to_str() - << " from server : " << res.move_as_error().to_string(); - return; + return envelope_send_query( + std::move(b), [this, blkid, promise = std::move(promise)](td::Result R) mutable -> void { + TRY_RESULT_PROMISE_PREFIX(promise, res, std::move(R), + PSLICE() << "cannot obtain block header for " << blkid.to_str() << " from server :"); + got_block_header_raw(std::move(res), std::move(promise), blkid); + }); +} + +bool TestNode::lookup_show_block(ton::ShardIdFull shard, int mode, td::uint64 arg) { + return lookup_block(shard, mode, arg, [this](td::Result R) { + if (R.is_error()) { + LOG(ERROR) << "unable to look up block: " << R.move_as_error(); } else { - auto F = ton::fetch_tl_object(res.move_as_ok(), true); - if (F.is_error()) { - LOG(ERROR) << "cannot parse answer to liteServer.getBlockHeader : " << res.move_as_error().to_string(); - } else { - auto f = F.move_as_ok(); - auto blk_id = ton::create_block_id(f->id_); - LOG(INFO) << "obtained block header for " << blk_id.to_str() << " from server"; - if (blk_id != blkid) { - LOG(ERROR) << "block id mismatch: expected data for block " << blkid.to_str() << ", obtained for " - << blk_id.to_str(); - } - td::actor::send_closure_later(Self, &TestNode::got_block_header, blk_id, std::move(f->header_proof_), f->mode_); - } + auto res = R.move_as_ok(); + show_block_header(res.blk_id, res.virt_blk_root, res.mode); + show_new_blkids(); } }); - return false; } -bool TestNode::lookup_block(ton::ShardIdFull shard, int mode, td::uint64 arg) { +bool TestNode::lookup_block(ton::ShardIdFull shard, int mode, td::uint64 arg, + td::Promise promise) { ton::BlockId id{shard, mode & 1 ? (td::uint32)arg : 0}; LOG(INFO) << "got block lookup request for " << id.to_str() << " with mode " << mode << " and argument " << arg; auto b = ton::serialize_tl_object(ton::create_tl_object( mode, ton::create_tl_lite_block_id_simple(id), arg, (td::uint32)arg), true); return envelope_send_query( - std::move(b), [Self = actor_id(this), id, mode, arg](td::Result res) -> void { - if (res.is_error()) { - LOG(ERROR) << "cannot look up block header for " << id.to_str() << " with mode " << mode << " and argument " - << arg << " from server : " << res.move_as_error().to_string(); - return; - } else { - auto F = ton::fetch_tl_object(res.move_as_ok(), true); - if (F.is_error()) { - LOG(ERROR) << "cannot parse answer to liteServer.lookupBlock : " << res.move_as_error().to_string(); - } else { - auto f = F.move_as_ok(); - auto blk_id = ton::create_block_id(f->id_); - LOG(INFO) << "obtained block header for " << blk_id.to_str() << " from server"; - td::actor::send_closure_later(Self, &TestNode::got_block_header, blk_id, std::move(f->header_proof_), - f->mode_); - } - } + std::move(b), [this, id, mode, arg, promise = std::move(promise)](td::Result R) mutable -> void { + TRY_RESULT_PROMISE_PREFIX(promise, res, std::move(R), + PSLICE() << "cannot look up block header for " << id.to_str() << " with mode " << mode + << " and argument " << arg << " from server :"); + got_block_header_raw(std::move(res), std::move(promise)); }); } +void TestNode::got_block_header_raw(td::BufferSlice res, td::Promise promise, + ton::BlockIdExt req_blkid) { + TRY_RESULT_PROMISE_PREFIX(promise, f, + ton::fetch_tl_object(std::move(res), true), + "cannot parse answer to liteServer.lookupBlock :"); + auto blk_id = ton::create_block_id(f->id_); + LOG(INFO) << "obtained block header for " << blk_id.to_str() << " from server (" << f->header_proof_.size() + << " data bytes)"; + if (req_blkid.is_valid() && blk_id != req_blkid) { + promise.set_error(td::Status::Error(PSLICE() << "block id mismatch: expected data for block " << req_blkid.to_str() + << ", obtained for " << blk_id.to_str())); + return; + } + TRY_RESULT_PROMISE_PREFIX(promise, root, vm::std_boc_deserialize(std::move(f->header_proof_)), + "cannot deserialize block header data :"); + bool ok = false; + td::Status E; + try { + auto virt_root = vm::MerkleProof::virtualize(root, 1); + if (virt_root.is_null()) { + promise.set_error(td::Status::Error(PSLICE() << "block header proof for block " << blk_id.to_str() + << " is not a valid Merkle proof")); + return; + } + ok = true; + promise.set_result(BlockHdrInfo{blk_id, std::move(root), std::move(virt_root), f->mode_}); + return; + } catch (vm::VmError& err) { + E = err.as_status(PSLICE() << "error processing header for " << blk_id.to_str() << " :"); + } catch (vm::VmVirtError& err) { + E = err.as_status(PSLICE() << "error processing header for " << blk_id.to_str() << " :"); + } + if (ok) { + LOG(ERROR) << std::move(E); + } else { + promise.set_error(std::move(E)); + } +} + bool TestNode::show_block_header(ton::BlockIdExt blkid, Ref root, int mode) { ton::RootHash vhash{root->get_hash().bits()}; if (vhash != blkid.root_hash) { @@ -2721,10 +2818,10 @@ void TestNode::got_block_proof(ton::BlockIdExt from, ton::BlockIdExt to, int mod register_blkid(chain->key_blkid); } register_blkid(chain->to); - auto now = static_cast(td::Clocks::system()); - if (!(mode & 1) || (chain->last_utime > now - 3600)) { + auto time = now(); + if (!(mode & 1) || (chain->last_utime > time - 3600)) { td::TerminalIO::out() << "last block in chain was generated at " << chain->last_utime << " (" - << now - chain->last_utime << " seconds ago)\n"; + << time - chain->last_utime << " seconds ago)\n"; } show_new_blkids(); } @@ -2740,93 +2837,710 @@ bool TestNode::get_creator_stats(ton::BlockIdExt blkid, int mode, unsigned req_c if (!(mode & 1)) { start_after.set_zero(); } - auto b = ton::serialize_tl_object(ton::create_tl_object( - mode, ton::create_tl_lite_block_id(blkid), req_count, start_after, min_utime), - true); + auto osp = std::make_unique(); + auto& os = *osp; + return get_creator_stats( + blkid, mode, req_count, start_after, min_utime, + [min_utime, &os](const td::Bits256& key, const block::DiscountedCounter& mc_cnt, + const block::DiscountedCounter& shard_cnt) -> bool { + os << key.to_hex() << " mc_cnt:" << mc_cnt << " shard_cnt:" << shard_cnt << std::endl; + return true; + }, + td::PromiseCreator::lambda([os = std::move(osp)](td::Result res) { + if (res.is_error()) { + LOG(ERROR) << "error obtaining creator stats: " << res.move_as_error(); + } else { + if (res.ok().is_zero()) { + *os << "(complete)" << std::endl; + } else { + *os << "(incomplete, repeat query from " << res.move_as_ok().to_hex() << " )" << std::endl; + } + td::TerminalIO::out() << os->str(); + } + })); +} + +bool TestNode::get_creator_stats(ton::BlockIdExt blkid, int mode, unsigned req_count, ton::Bits256 start_after, + ton::UnixTime min_utime, TestNode::creator_stats_func_t func, + td::Promise promise) { + return get_creator_stats(blkid, req_count, min_utime, std::move(func), + std::make_unique(mode | 0x10000, start_after), + promise.wrap([](auto&& p) { return p->last_key; })); +} + +bool TestNode::get_creator_stats(ton::BlockIdExt blkid, unsigned req_count, ton::UnixTime min_utime, + TestNode::creator_stats_func_t func, std::unique_ptr state, + td::Promise> promise) { + if (!(ready_ && !client_.empty())) { + promise.set_error(td::Status::Error("server connection not ready")); + return false; + } + if (!state) { + promise.set_error(td::Status::Error("null CreatorStatsRes")); + return false; + } + if (!blkid.is_masterchain_ext()) { + promise.set_error(td::Status::Error("only masterchain blocks contain block creator statistics")); + return false; + } + if (!(state->mode & 1)) { + state->last_key.set_zero(); + } + auto b = ton::serialize_tl_object( + ton::create_tl_object( + state->mode & 0xff, ton::create_tl_lite_block_id(blkid), req_count, state->last_key, min_utime), + true); LOG(INFO) << "requesting up to " << req_count << " block creator stats records with respect to masterchain block " - << blkid.to_str() << " starting from validator public key " << start_after.to_hex() << " created after " - << min_utime << " (mode=" << mode << ")"; - return envelope_send_query(std::move(b), [Self = actor_id(this), mode, blkid, req_count, start_after, - min_utime](td::Result R) { - if (R.is_error()) { - return; - } - auto F = ton::fetch_tl_object(R.move_as_ok(), true); - if (F.is_error()) { - LOG(ERROR) << "cannot parse answer to liteServer.getValidatorStats"; - } else { - auto f = F.move_as_ok(); - td::actor::send_closure_later(Self, &TestNode::got_creator_stats, blkid, ton::create_block_id(f->id_), mode, - f->mode_, start_after, min_utime, std::move(f->state_proof_), - std::move(f->data_proof_), f->count_, req_count, f->complete_); - } - }); + << blkid.to_str() << " starting from validator public key " << state->last_key.to_hex() << " created after " + << min_utime << " (mode=" << state->mode << ")"; + return envelope_send_query( + std::move(b), [this, blkid, req_count, state = std::move(state), min_utime, func = std::move(func), + promise = std::move(promise)](td::Result R) mutable { + TRY_RESULT_PROMISE(promise, res, std::move(R)); + TRY_RESULT_PROMISE_PREFIX(promise, f, + ton::fetch_tl_object(std::move(res), true), + "cannot parse answer to liteServer.getValidatorStats"); + got_creator_stats(blkid, ton::create_block_id(f->id_), f->mode_, min_utime, std::move(f->state_proof_), + std::move(f->data_proof_), f->count_, req_count, f->complete_, std::move(func), + std::move(state), std::move(promise)); + }); } -void TestNode::got_creator_stats(ton::BlockIdExt req_blkid, ton::BlockIdExt blkid, int req_mode, int mode, - td::Bits256 start_after, ton::UnixTime min_utime, td::BufferSlice state_proof, - td::BufferSlice data_proof, int count, int req_count, bool complete) { +void TestNode::got_creator_stats(ton::BlockIdExt req_blkid, ton::BlockIdExt blkid, int mode, ton::UnixTime min_utime, + td::BufferSlice state_proof, td::BufferSlice data_proof, int count, int req_count, + bool complete, TestNode::creator_stats_func_t func, + std::unique_ptr status, + td::Promise> promise) { LOG(INFO) << "got answer to getValidatorStats query: " << count << " records out of " << req_count << ", " << (complete ? "complete" : "incomplete"); if (!blkid.is_masterchain_ext()) { - LOG(ERROR) << "reference block " << blkid.to_str() - << " for block creator statistics is not a valid masterchain block"; + promise.set_error(td::Status::Error(PSLICE() << "reference block " << blkid.to_str() + << " for block creator statistics is not a valid masterchain block")); return; } if (count > req_count) { - LOG(ERROR) << "obtained " << count << " answers to getValidatorStats query, but only " << req_count - << " were requested"; + promise.set_error(td::Status::Error(PSLICE() + << "obtained " << count << " answers to getValidatorStats query, but only " + << req_count << " were requested")); return; } if (blkid != req_blkid) { - LOG(ERROR) << "answer to getValidatorStats refers to masterchain block " << blkid.to_str() - << " different from requested " << req_blkid.to_str(); + promise.set_error(td::Status::Error(PSLICE() + << "answer to getValidatorStats refers to masterchain block " << blkid.to_str() + << " different from requested " << req_blkid.to_str())); return; } - auto R = block::check_extract_state_proof(blkid, state_proof.as_slice(), data_proof.as_slice()); - if (R.is_error()) { - LOG(ERROR) << "masterchain state proof for " << blkid.to_str() << " is invalid : " << R.move_as_error().to_string(); - return; + TRY_RESULT_PROMISE_PREFIX(promise, state, + block::check_extract_state_proof(blkid, state_proof.as_slice(), data_proof.as_slice()), + PSLICE() << "masterchain state proof for " << blkid.to_str() << " is invalid :"); + if (!(mode & 0x10000)) { + if (status->state_proof.is_null()) { + TRY_RESULT_PROMISE_PREFIX( + promise, state_root, vm::std_boc_deserialize(state_proof.as_slice()), + PSLICE() << "cannot deserialize masterchain state proof for " << blkid.to_str() << ": "); + status->state_proof = std::move(state_root); + } + TRY_RESULT_PROMISE_PREFIX( + promise, data_root, vm::std_boc_deserialize(data_proof.as_slice()), + PSLICE() << "cannot deserialize masterchain creators data proof for " << blkid.to_str() << ": "); + if (status->data_proof.is_null()) { + status->data_proof = std::move(data_root); + } else { + TRY_RESULT_PROMISE_PREFIX(promise, data_proof2, + vm::MerkleProof::combine_fast_status(status->data_proof, std::move(data_root)), + "cannot combine Merkle proofs for creator data"); + status->data_proof = std::move(data_proof2); + } } bool allow_eq = (mode & 3) != 1; - ton::Bits256 key{start_after}; + ton::Bits256 key{status->last_key}; std::ostringstream os; try { - auto dict = block::get_block_create_stats_dict(R.move_as_ok()); + auto dict = block::get_block_create_stats_dict(std::move(state)); if (!dict) { - LOG(ERROR) << "cannot extract BlockCreateStats from mc state"; + promise.set_error(td::Status::Error("cannot extract BlockCreateStats from mc state")); return; } for (int i = 0; i < count + (int)complete; i++) { auto v = dict->lookup_nearest_key(key, true, allow_eq); if (v.is_null()) { if (i != count) { - LOG(ERROR) << "could fetch only " << i << " CreatorStats entries out of " << count - << " declared in answer to getValidatorStats"; + promise.set_error(td::Status::Error(PSLICE() << "could fetch only " << i << " CreatorStats entries out of " + << count << " declared in answer to getValidatorStats")); return; } break; } block::DiscountedCounter mc_cnt, shard_cnt; if (!block::unpack_CreatorStats(std::move(v), mc_cnt, shard_cnt)) { - LOG(ERROR) << "invalid CreatorStats record with key " << key.to_hex(); + promise.set_error(td::Status::Error(PSLICE() << "invalid CreatorStats record with key " << key.to_hex())); return; } if (mc_cnt.modified_since(min_utime) || shard_cnt.modified_since(min_utime)) { - os << key.to_hex() << " mc_cnt:" << mc_cnt << " shard_cnt:" << shard_cnt << std::endl; + func(key, mc_cnt, shard_cnt); } allow_eq = false; } if (complete) { - os << "(complete)" << std::endl; + status->last_key.set_zero(); + status->complete = true; + promise.set_result(std::move(status)); + } else if (!(status->mode & 0x100)) { + status->last_key = key; + promise.set_result(std::move(status)); } else { - os << "(incomplete, repeat query from " << key.to_hex() << " )" << std::endl; + // incomplete, send new query to fetch next entries + status->last_key = key; + status->mode |= 1; + get_creator_stats(blkid, req_count, min_utime, std::move(func), std::move(status), std::move(promise)); } - td::TerminalIO::out() << os.str(); } catch (vm::VmError& err) { - LOG(ERROR) << "error while traversing block creator stats: " << err.get_msg(); + promise.set_error(err.as_status("error while traversing block creator stats:")); + } catch (vm::VmVirtError& err) { + promise.set_error(err.as_status("virtualization error while traversing block creator stats:")); + } +} + +bool TestNode::check_validator_load(int start_time, int end_time, int mode, std::string file_pfx) { + int time = now(); + if (start_time <= 0) { + start_time += time; + } + if (end_time <= 0) { + end_time += time; + } + if (start_time >= end_time) { + return set_error("end time must be later than start time"); + } + LOG(INFO) << "requesting masterchain blocks corresponding to unixtime " << start_time << " and " << end_time; + auto P = td::split_promise([this, mode, file_pfx](td::Result> R) { + if (R.is_error()) { + LOG(ERROR) << "cannot obtain block info: " << R.move_as_error(); + return; + } + auto res = R.move_as_ok(); + continue_check_validator_load(res.first.blk_id, res.first.proof, res.second.blk_id, res.second.proof, mode, + file_pfx); + }); + lookup_block(ton::ShardIdFull(ton::masterchainId), 4, start_time, std::move(P.first)); + return lookup_block(ton::ShardIdFull(ton::masterchainId), 4, end_time, std::move(P.second)); +} + +void TestNode::continue_check_validator_load(ton::BlockIdExt blkid1, Ref root1, ton::BlockIdExt blkid2, + Ref root2, int mode, std::string file_pfx) { + LOG(INFO) << "continue_check_validator_load for blocks " << blkid1.to_str() << " and " << blkid2.to_str() + << " : requesting configuration parameter #34"; + auto P = td::split_promise( + [this, blkid1, root1, blkid2, root2, mode, file_pfx](td::Result> R) mutable { + if (R.is_error()) { + LOG(ERROR) << "cannot obtain configuration parameter #34 : " << R.move_as_error(); + return; + } + auto res = R.move_as_ok(); + root1 = vm::MerkleProof::combine_fast(std::move(root1), std::move(res.first.state_proof)); + root2 = vm::MerkleProof::combine_fast(std::move(root2), std::move(res.second.state_proof)); + if (root1.is_null() || root2.is_null()) { + LOG(ERROR) << "cannot merge block header proof with block state proof"; + return; + } + auto info1 = std::make_unique(blkid1, std::move(root1), std::move(res.first.config_proof), + std::move(res.first.config)); + auto info2 = std::make_unique(blkid2, std::move(root2), std::move(res.second.config_proof), + std::move(res.second.config)); + continue_check_validator_load2(std::move(info1), std::move(info2), mode, file_pfx); + }); + get_config_params_ext(blkid1, std::move(P.first), 0x4000, "", {28, 34}); + get_config_params_ext(blkid2, std::move(P.second), 0x4000, "", {28, 34}); +} + +bool TestNode::ValidatorLoadInfo::unpack_vset() { + if (!config) { + return false; + } + auto vset_root = config->get_config_param(34); + if (vset_root.is_null()) { + LOG(ERROR) << "no configuration parameter 34 for block " << blk_id.to_str(); + return false; + } + auto R = block::Config::unpack_validator_set(std::move(vset_root)); + if (R.is_error()) { + LOG(ERROR) << "cannot unpack validator set from configuration parameter 34 of block " << blk_id.to_str() << " : " + << R.move_as_error(); + return false; + } + vset = R.move_as_ok(); + valid_since = vset->utime_since; + vset_map = vset->compute_validator_map(); + return true; +} + +bool TestNode::ValidatorLoadInfo::store_record(const td::Bits256& key, const block::DiscountedCounter& mc_cnt, + const block::DiscountedCounter& shard_cnt) { + if (!(mc_cnt.is_valid() && shard_cnt.is_valid())) { + return false; + } + if (mc_cnt.total >= (1ULL << 60) || shard_cnt.total >= (1ULL << 60)) { + return false; + } + if (key.is_zero()) { + created_total.first = (td::int64)mc_cnt.total; + created_total.second = (td::int64)shard_cnt.total; + return true; + } + auto it = vset_map.find(key); + if (it == vset_map.end()) { + return false; + } + created.at(it->second) = std::make_pair(mc_cnt.total, shard_cnt.total); + return true; +} + +bool TestNode::load_creator_stats(std::unique_ptr load_to, + td::Promise> promise, bool need_proofs) { + if (!load_to) { + promise.set_error(td::Status::Error("no ValidatorLoadInfo")); + return false; + } + auto& info = *load_to; + info.created_total.first = info.created_total.second = 0; + info.created.resize(0); + info.created.resize(info.vset->total, std::make_pair(0, 0)); + ton::UnixTime min_utime = info.valid_since - 1000; + return get_creator_stats( + info.blk_id, 1000, min_utime, + [min_utime, &info](const td::Bits256& key, const block::DiscountedCounter& mc_cnt, + const block::DiscountedCounter& shard_cnt) -> bool { + info.store_record(key, mc_cnt, shard_cnt); + return true; + }, + std::make_unique(need_proofs ? 0x100 : 0x10100), + td::PromiseCreator::lambda([load_to = std::move(load_to), promise = std::move(promise)]( + td::Result> R) mutable { + TRY_RESULT_PROMISE_PREFIX(promise, res, std::move(R), "error obtaining creator stats:"); + if (!res->complete) { + promise.set_error(td::Status::Error("incomplete creator stats")); + return; + } + // merge + load_to->state_proof = + vm::MerkleProof::combine_fast(std::move(load_to->state_proof), std::move(res->state_proof)); + load_to->data_proof = vm::MerkleProof::combine_fast(std::move(load_to->data_proof), std::move(res->data_proof)); + promise.set_result(std::move(load_to)); + })); +} + +void TestNode::continue_check_validator_load2(std::unique_ptr info1, + std::unique_ptr info2, int mode, + std::string file_pfx) { + LOG(INFO) << "continue_check_validator_load2 for blocks " << info1->blk_id.to_str() << " and " + << info1->blk_id.to_str() << " : requesting block creators data"; + if (!(info1->unpack_vset() && info2->unpack_vset())) { + return; + } + if (info1->valid_since != info2->valid_since) { + LOG(ERROR) << "blocks appear to have different validator sets"; + return; + } + LOG(INFO) << "validator sets valid since " << info1->valid_since; + auto P = td::split_promise( + [this, mode, + file_pfx](td::Result, std::unique_ptr>> R) { + if (R.is_error()) { + LOG(ERROR) << "cannot load block creation statistics : " << R.move_as_error(); + return; + } + auto res = R.move_as_ok(); + continue_check_validator_load3(std::move(res.first), std::move(res.second), mode, file_pfx); + }); + load_creator_stats(std::move(info1), std::move(P.first), true); + load_creator_stats(std::move(info2), std::move(P.second), true); +} + +// computes the probability of creating <= x masterchain blocks if the expected value is y +static double create_prob(int x, double y) { + if (x < 0 || y < 0) { + return .5; + } + if (x >= y) { + return .5; + } + if (x <= 20) { + // Poisson + double t = exp(-y), s = t; + for (int n = 1; n <= x; n++) { + s += t = (t * y) / n; + } + return s; + } + // normal approximation + double z = (x - y) / sqrt(2. * y); + return (1. + erf(z)) / 2; +} + +static double shard_create_prob(int x, double y, double chunk_size) { + if (x < 0 || y < 0) { + return .5; + } + if (x >= y) { + return .5; + } + double y0 = y / chunk_size; // expected chunks + if (!x) { + return y0 > 100 ? 0 : exp(-y0); // Poisson approximation for having participated in zero chunks + } + // at least ten chunks, normal approximation + double z = (x - y) / sqrt(2. * y * chunk_size); + return (1. + erf(z)) / 2; +} + +void TestNode::continue_check_validator_load3(std::unique_ptr info1, + std::unique_ptr info2, int mode, + std::string file_pfx) { + LOG(INFO) << "continue_check_validator_load3 for blocks " << info1->blk_id.to_str() << " and " + << info1->blk_id.to_str() << " with mode=" << mode << " and file prefix `" << file_pfx + << "`: comparing block creators data"; + if (info1->created_total.first <= 0 || info2->created_total.first <= 0) { + LOG(ERROR) << "no total created blocks statistics"; + return; + } + td::TerminalIO::out() << "total: (" << info1->created_total.first << "," << info1->created_total.second << ") -> (" + << info2->created_total.first << "," << info2->created_total.second << ")\n"; + auto x = info2->created_total.first - info1->created_total.first; + auto y = info2->created_total.second - info1->created_total.second; + td::int64 xs = 0, ys = 0; + if (x <= 0 || y < 0 || (x | y) >= (1u << 31)) { + LOG(ERROR) << "impossible situation: zero or no blocks created: " << x << " masterchain blocks, " << y + << " shardchain blocks"; + return; + } + std::pair created_total{(int)x, (int)y}; + int count = info1->vset->total; + CHECK(info2->vset->total == count); + CHECK((int)info1->created.size() == count); + CHECK((int)info2->created.size() == count); + std::vector> d; + d.reserve(count); + for (int i = 0; i < count; i++) { + auto x1 = info2->created[i].first - info1->created[i].first; + auto y1 = info2->created[i].second - info1->created[i].second; + if (x1 < 0 || y1 < 0 || (x1 | y1) >= (1u << 31)) { + LOG(ERROR) << "impossible situation: validator #i created a negative amount of blocks: " << x1 + << " masterchain blocks, " << y1 << " shardchain blocks"; + return; + } + xs += x1; + ys += y1; + d.emplace_back((int)x1, (int)y1); + td::TerminalIO::out() << "val #" << i << ": created (" << x1 << "," << y1 << ") ; was (" << info1->created[i].first + << "," << info1->created[i].second << ")\n"; + } + if (xs != x || ys != y) { + LOG(ERROR) << "cannot account for all blocks created: total is (" << x << "," << y + << "), but the sum for all validators is (" << xs << "," << ys << ")"; + return; + } + td::TerminalIO::out() << "total: (" << x << "," << y << ")\n"; + auto ccfg = block::Config::unpack_catchain_validators_config(info2->config->get_config_param(28)); + auto ccfg_old = block::Config::unpack_catchain_validators_config(info1->config->get_config_param(28)); + if (ccfg.shard_val_num != ccfg_old.shard_val_num || ccfg.shard_val_num <= 0) { + LOG(ERROR) << "shard validator group size changed from " << ccfg_old.shard_val_num << " to " << ccfg.shard_val_num + << ", or is not positive"; + return; + } + int shard_count = ccfg.shard_val_num, main_count = info2->vset->main; + if (info1->vset->main != main_count || main_count <= 0) { + LOG(ERROR) << "masterchain validator group size changed from " << info1->vset->main << " to " << main_count + << ", or is not positive"; + return; + } + int cnt = 0, cnt_ok = 0; + double chunk_size = ccfg.shard_val_lifetime / 3. / shard_count; + block::MtCarloComputeShare shard_share(shard_count, info2->vset->export_scaled_validator_weights()); + for (int i = 0; i < count; i++) { + int x1 = d[i].first, y1 = d[i].second; + double xe = (i < main_count ? (double)xs / main_count : 0); + double ye = shard_share[i] * (double)ys / shard_count; + td::Bits256 pk = info2->vset->list[i].pubkey.as_bits256(); + double p1 = create_prob(x1, .9 * xe), p2 = shard_create_prob(y1, .9 * ye, chunk_size); + td::TerminalIO::out() << "val #" << i << ": pubkey " << pk.to_hex() << ", blocks created (" << x1 << "," << y1 + << "), expected (" << xe << "," << ye << "), probabilities " << p1 << " and " << p2 << "\n"; + if (std::min(p1, p2) < .00001) { + LOG(ERROR) << "validator #" << i << " with pubkey " << pk.to_hex() + << " : serious misbehavior detected: created less than 90% of the expected amount of blocks with " + "probability 99.999% : created (" + << x1 << "," << y1 << "), expected (" << xe << "," << ye << ") masterchain/shardchain blocks\n"; + if (mode & 2) { + auto st = write_val_create_proof(*info1, *info2, i, true, file_pfx, ++cnt); + if (st.is_error()) { + LOG(ERROR) << "cannot create proof: " << st.move_as_error(); + } else { + cnt_ok++; + } + } + } else if (std::min(p1, p2) < .001) { + LOG(ERROR) << "validator #" << i << " with pubkey " << pk.to_hex() + << " : moderate misbehavior detected: created less than 90% of the expected amount of blocks with " + "probability 99.9% : created (" + << x1 << "," << y1 << "), expected (" << xe << "," << ye << ") masterchain/shardchain blocks\n"; + if ((mode & 3) == 2) { + auto st = write_val_create_proof(*info1, *info2, i, false, file_pfx, ++cnt); + if (st.is_error()) { + LOG(ERROR) << "cannot create proof: " << st.move_as_error(); + } else { + cnt_ok++; + } + } + } + } + if (cnt > 0) { + LOG(INFO) << cnt_ok << " out of " << cnt << " proofs written to " << file_pfx << "-*.boc"; + } +} + +td::Status TestNode::write_val_create_proof(TestNode::ValidatorLoadInfo& info1, TestNode::ValidatorLoadInfo& info2, + int idx, bool severe, std::string file_pfx, int cnt) { + std::string filename = PSTRING() << file_pfx << '-' << cnt << ".boc"; + if (!info1.has_data()) { + return td::Status::Error("first block information is incomplete"); + } + if (!info2.has_data()) { + return td::Status::Error("second block information is incomplete"); + } + LOG(INFO) << "creating proof file " << filename; + TRY_STATUS(info1.check_header_proof(&info1.block_created_at, &info1.end_lt)); + TRY_STATUS(info2.check_header_proof(&info2.block_created_at, &info2.end_lt)); + td::Bits256 val_pk1, val_pk2; + TRY_RESULT(prod1, info1.build_producer_info(idx, &val_pk1)); + TRY_RESULT(prod2, info2.build_producer_info(idx, &val_pk2)); + if (val_pk1 != val_pk2) { + return td::Status::Error("validator public key mismatch"); + } + int severity = (severe ? 2 : 1); + td::RefInt256 fine = td::make_refint(1000000000); + unsigned fine_part = 0xffffffff / 16; // 1/16 + Ref cpl_descr, complaint; + vm::CellBuilder cb; + // no_blk_gen_diff prod_info_old:^ProducerInfo prod_info_new:^ProducerInfo = ComplaintDescr + if (!(block::gen::t_ComplaintDescr.cell_pack_no_blk_gen_diff(cpl_descr, prod1, prod2) && + cb.store_long_bool(0xbc, 8) // validator_complaint#bc + && cb.store_bits_bool(val_pk1) // validator_pubkey:uint256 + && cb.store_ref_bool(cpl_descr) // description:^ComplaintDescr + && cb.store_long_bool(now(), 32) // created_at:uint32 + && cb.store_long_bool(severity, 8) // severity:uint8 + && cb.store_zeroes_bool(256) // reward_addr:uint256 + && cb.store_zeroes_bool(4) // paid:Grams + && block::tlb::t_Grams.store_integer_ref(cb, std::move(fine)) // suggested_fine:Grams + && cb.store_long_bool(fine_part, 32) // suggested_fine_part:uint32 + && cb.finalize_to(complaint))) { + return td::Status::Error("cannot serialize ValidatorComplaint"); + } + if (verbosity >= 5) { + std::ostringstream os; + os << "complaint: "; + block::gen::t_ValidatorComplaint.print_ref(print_limit_, os, complaint); + td::TerminalIO::out() << os.str() << std::endl; + } + if (!block::gen::t_ComplaintDescr.validate_ref(cpl_descr)) { + return td::Status::Error("created an invalid ComplaintDescr"); + } + if (!block::gen::t_ValidatorComplaint.validate_ref(complaint)) { + return td::Status::Error("created an invalid ValidatorComplaint"); + } + TRY_RESULT_PREFIX(boc, vm::std_boc_serialize(complaint, 2), "cannot create boc:"); + auto size = boc.size(); + TRY_STATUS_PREFIX(td::write_file(filename, std::move(boc)), PSLICE() << "cannot save file `" << filename << "` :"); + td::TerminalIO::out() << "saved validator misbehavior proof into file `" << filename << "` (" << size + << " bytes written)" << std::endl; + + return td::Status::OK(); +} + +td::Status TestNode::ValidatorLoadInfo::check_header_proof(ton::UnixTime* save_utime, ton::LogicalTime* save_lt) const { + auto state_virt_root = vm::MerkleProof::virtualize(std::move(data_proof), 1); + if (state_virt_root.is_null()) { + return td::Status::Error("account state proof is invalid"); + } + td::Bits256 state_hash = state_virt_root->get_hash().bits(); + TRY_STATUS(block::check_block_header_proof(vm::MerkleProof::virtualize(state_proof, 1), blk_id, &state_hash, true, + save_utime, save_lt)); + return td::Status::OK(); +} + +static bool visit(Ref cell); + +static bool visit(const vm::CellSlice& cs) { + auto cnt = cs.size_refs(); + bool res = true; + for (unsigned i = 0; i < cnt; i++) { + res &= visit(cs.prefetch_ref(i)); + } + return res; +} + +static bool visit(Ref cell) { + if (cell.is_null()) { + return true; + } + vm::CellSlice cs{vm::NoVm{}, std::move(cell)}; + return visit(cs); +} + +static bool visit(Ref cs_ref) { + return cs_ref.is_null() || visit(*cs_ref); +} + +td::Result> TestNode::ValidatorLoadInfo::build_proof(int idx, td::Bits256* save_pubkey) const { + try { + auto state_virt_root = vm::MerkleProof::virtualize(std::move(data_proof), 1); + if (state_virt_root.is_null()) { + return td::Status::Error("account state proof is invalid"); + } + vm::MerkleProofBuilder pb{std::move(state_virt_root)}; + TRY_RESULT(cfg, block::Config::extract_from_state(pb.root())); + visit(cfg->get_config_param(28)); + block::gen::ValidatorSet::Record_validators_ext rec; + if (!tlb::unpack_cell(cfg->get_config_param(34), rec)) { + return td::Status::Error("cannot unpack ValidatorSet"); + } + vm::Dictionary vdict{rec.list, 16}; + auto entry = vdict.lookup(td::BitArray<16>(idx)); + if (entry.is_null()) { + return td::Status::Error("validator entry not found"); + } + Ref pk; + block::gen::ValidatorDescr::Record_validator rec1; + block::gen::ValidatorDescr::Record_validator_addr rec2; + if (tlb::csr_unpack(entry, rec1)) { + pk = std::move(rec1.public_key); + } else if (tlb::csr_unpack(std::move(entry), rec2)) { + pk = std::move(rec2.public_key); + } else { + return td::Status::Error("cannot unpack ValidatorDescr"); + } + block::gen::SigPubKey::Record rec3; + if (!tlb::csr_unpack(std::move(pk), rec3)) { + return td::Status::Error("cannot unpack ed25519_pubkey"); + } + if (save_pubkey) { + *save_pubkey = rec3.pubkey; + } + visit(std::move(entry)); + auto dict = block::get_block_create_stats_dict(pb.root()); + if (!dict) { + return td::Status::Error("cannot extract BlockCreateStats from mc state"); + } + visit(dict->lookup(rec3.pubkey)); + visit(dict->lookup(td::Bits256::zero())); + return pb.extract_proof(); + } catch (vm::VmError& err) { + return err.as_status("cannot build proof: "); + } catch (vm::VmVirtError& err) { + return err.as_status("cannot build proof: "); + } +} + +td::Result> TestNode::ValidatorLoadInfo::build_producer_info(int idx, td::Bits256* save_pubkey) const { + TRY_RESULT(proof, build_proof(idx, save_pubkey)); + vm::CellBuilder cb; + Ref res; + if (!(cb.store_long_bool(0x34, 8) // prod_info#34 + && cb.store_long_bool(block_created_at, 32) // utime:uint32 + && block::tlb::t_ExtBlkRef.store(cb, blk_id, end_lt) // mc_blk_ref:ExtBlkRef + && cb.store_ref_bool(state_proof) // state_proof:^Cell + && cb.store_ref_bool(proof) // prod_proof:^Cell = ProducerInfo + && cb.finalize_to(res))) { + return td::Status::Error("cannot construct ProducerInfo"); + } + if (!block::gen::t_ProducerInfo.validate_ref(res)) { + return td::Status::Error("constructed ProducerInfo failed to pass automated validity checks"); + } + return std::move(res); +} + +td::Status TestNode::check_validator_load_proof(std::string filename) { + TRY_RESULT_PREFIX(data, td::read_file(filename), "cannot read proof file:"); + TRY_RESULT_PREFIX(root, vm::std_boc_deserialize(std::move(data)), + PSTRING() << "cannot deserialize boc from file `" << filename << "`:"); + if (verbosity >= 5) { + std::ostringstream os; + os << "complaint: "; + block::gen::t_ValidatorComplaint.print_ref(print_limit_, os, root); + td::TerminalIO::out() << os.str() << std::endl; + } + if (!block::gen::t_ValidatorComplaint.validate_ref(root)) { + return td::Status::Error("proof file does not contain a valid ValidatorComplaint"); + } + block::gen::ValidatorComplaint::Record rec; + if (!tlb::unpack_cell(root, rec)) { + return td::Status::Error("cannot unpack ValidatorComplaint"); + } + auto cs = vm::load_cell_slice(rec.description); + int tag = block::gen::t_ComplaintDescr.get_tag(cs); + if (tag < 0) { + return td::Status::Error("ComplaintDescr has an unknown tag"); + } + if (tag != block::gen::ComplaintDescr::no_blk_gen_diff) { + return td::Status::Error("can check only ComplaintDescr of type no_blk_gen_diff"); + } + block::gen::ComplaintDescr::Record_no_blk_gen_diff crec; + if (!tlb::unpack_exact(cs, crec)) { + return td::Status::Error("cannot unpack ComplaintDescr"); + } + TRY_RESULT_PREFIX(info1, ValidatorLoadInfo::preinit_from_producer_info(crec.prod_info_old), + "cannot unpack ProducerInfo in prod_info_old:") + TRY_RESULT_PREFIX(info2, ValidatorLoadInfo::preinit_from_producer_info(crec.prod_info_new), + "cannot unpack ProducerInfo in prod_info_new:") + // ??? + return td::Status::OK(); +} + +td::Result> TestNode::ValidatorLoadInfo::preinit_from_producer_info( + Ref prod_info) { + if (prod_info.is_null()) { + return td::Status::Error("ProducerInfo cell is null"); + } + if (!block::gen::t_ProducerInfo.validate_ref(prod_info)) { + return td::Status::Error("invalid ProducerInfo"); + } + block::gen::ProducerInfo::Record rec; + ton::BlockIdExt blk_id; + ton::LogicalTime end_lt; + if (!(tlb::unpack_cell(prod_info, rec) && + block::tlb::t_ExtBlkRef.unpack(std::move(rec.mc_blk_ref), blk_id, &end_lt))) { + return td::Status::Error("cannot unpack ProducerInfo"); + } + auto info = std::make_unique(blk_id, std::move(rec.state_proof), std::move(rec.prod_proof)); + CHECK(info); + info->end_lt = end_lt; + info->block_created_at = rec.utime; + TRY_STATUS_PREFIX(info->init_check_proofs(), "error checking block/state proofs:"); + return std::move(info); +} + +td::Status TestNode::ValidatorLoadInfo::init_check_proofs() { + try { + ton::UnixTime utime; + ton::LogicalTime lt; + TRY_STATUS(check_header_proof(&utime, <)); + if (utime != block_created_at) { + return td::Status::Error(PSLICE() << "incorrect block creation time: declared " << block_created_at << ", actual " + << utime); + } + if (lt != end_lt) { + return td::Status::Error(PSLICE() << "incorrect block logical time: declared " << end_lt << ", actual " << lt); + } + auto vstate = vm::MerkleProof::virtualize(data_proof, 1); + if (vstate.is_null()) { + return td::Status::Error(PSLICE() << "cannot virtualize state of block " << blk_id.to_str()); + } + TRY_RESULT_PREFIX_ASSIGN(config, block::Config::extract_from_state(vstate, 0), "cannot unpack configuration:"); + + // ... ??? ... + return td::Status::OK(); + } catch (vm::VmError& err) { + return err.as_status("vm error:"); } catch (vm::VmVirtError& err) { - LOG(ERROR) << "virtualization error while traversing block creator stats: " << err.get_msg(); + return err.as_status("virtualization error:"); } } diff --git a/submodules/ton/tonlib-src/lite-client/lite-client.h b/submodules/ton/tonlib-src/lite-client/lite-client.h index 24af7f81282..2730f9e5ae9 100644 --- a/submodules/ton/tonlib-src/lite-client/lite-client.h +++ b/submodules/ton/tonlib-src/lite-client/lite-client.h @@ -33,6 +33,7 @@ #include "vm/cells.h" #include "vm/stack.hpp" #include "block/block.h" +#include "block/mc-config.h" #include "td/utils/filesystem.h" using td::Ref; @@ -89,6 +90,9 @@ class TestNode : public td::actor::Actor { std::unique_ptr make_callback(); + using creator_stats_func_t = + std::function; + struct TransId { ton::Bits256 acc_addr; ton::LogicalTime trans_lt; @@ -98,6 +102,71 @@ class TestNode : public td::actor::Actor { } }; + struct BlockHdrInfo { + ton::BlockIdExt blk_id; + Ref proof, virt_blk_root; + int mode; + BlockHdrInfo() : mode(-1) { + } + BlockHdrInfo(const ton::BlockIdExt blk_id_, Ref proof_, Ref vroot_, int mode_) + : blk_id(blk_id_), proof(std::move(proof_)), virt_blk_root(std::move(vroot_)), mode(mode_) { + } + }; + + struct ConfigInfo { + std::unique_ptr config; + Ref state_proof, config_proof; + ConfigInfo() = default; + ConfigInfo(std::unique_ptr config_, Ref state_proof_, Ref config_proof_) + : config(std::move(config_)), state_proof(std::move(state_proof_)), config_proof(std::move(config_proof_)) { + } + }; + + struct CreatorStatsRes { + int mode; + bool complete{false}; + td::Bits256 last_key; + Ref state_proof, data_proof; + CreatorStatsRes(int mode_ = 0) : mode(mode_) { + last_key.set_zero(); + } + CreatorStatsRes(int mode_, const td::Bits256& key_, Ref st_proof_ = {}, Ref dproof_ = {}) + : mode(mode_), last_key(key_), state_proof(std::move(st_proof_)), data_proof(std::move(dproof_)) { + } + }; + + struct ValidatorLoadInfo { + ton::BlockIdExt blk_id; + Ref state_proof, data_proof, virt_root; + std::unique_ptr config; + ton::UnixTime block_created_at{0}; + ton::UnixTime valid_since{0}; + ton::LogicalTime end_lt{0}; + std::unique_ptr vset; + std::map vset_map; + std::pair created_total; + std::vector> created; + ValidatorLoadInfo(ton::BlockIdExt blkid, Ref root, Ref root2, + std::unique_ptr cfg = {}) + : blk_id(blkid) + , state_proof(std::move(root)) + , data_proof(std::move(root2)) + , config(std::move(cfg)) + , valid_since(0) { + } + bool unpack_vset(); + bool store_record(const td::Bits256& key, const block::DiscountedCounter& mc_cnt, + const block::DiscountedCounter& shard_cnt); + bool has_data() const { + return blk_id.is_masterchain_ext() && state_proof.not_null() && data_proof.not_null() && config; + } + td::Status check_header_proof(ton::UnixTime* save_utime = nullptr, ton::LogicalTime* save_lt = nullptr) const; + td::Result> build_proof(int idx, td::Bits256* save_pubkey = nullptr) const; + td::Result> build_producer_info(int idx, td::Bits256* save_pubkey = nullptr) const; + td::Status init_check_proofs(); + static td::Result> preinit_from_producer_info(Ref prod_info); + }; + void run_init_queries(); char cur() const { return *parse_ptr_; @@ -144,18 +213,24 @@ class TestNode : public td::actor::Actor { bool show_dns_record(std::ostream& os, int cat, Ref value, bool raw_dump); bool get_all_shards(std::string filename = "", bool use_last = true, ton::BlockIdExt blkid = {}); void got_all_shards(ton::BlockIdExt blk, td::BufferSlice proof, td::BufferSlice data, std::string filename); - bool get_config_params(ton::BlockIdExt blkid, td::Promise do_after, int mode = 0, std::string filename = "", - std::vector params = {}); - void got_config_params(ton::BlockIdExt req_blkid, ton::BlockIdExt blkid, td::BufferSlice state_proof, - td::BufferSlice cfg_proof, int mode, std::string filename, std::vector params, - td::Promise do_after); + bool parse_get_config_params(ton::BlockIdExt blkid, int mode = 0, std::string filename = "", + std::vector params = {}); + bool get_config_params(ton::BlockIdExt blkid, td::Promise> promise, int mode = 0, + std::string filename = "", std::vector params = {}); + bool get_config_params_ext(ton::BlockIdExt blkid, td::Promise promise, int mode = 0, + std::string filename = "", std::vector params = {}); + void got_config_params(ton::BlockIdExt req_blkid, int mode, std::string filename, std::vector params, + td::Result R, td::Promise promise); bool get_block(ton::BlockIdExt blk, bool dump = false); void got_block(ton::BlockIdExt blkid, td::BufferSlice data, bool dump); bool get_state(ton::BlockIdExt blk, bool dump = false); void got_state(ton::BlockIdExt blkid, ton::RootHash root_hash, ton::FileHash file_hash, td::BufferSlice data, bool dump); - bool get_block_header(ton::BlockIdExt blk, int mode); - bool lookup_block(ton::ShardIdFull shard, int mode, td::uint64 arg); + bool get_show_block_header(ton::BlockIdExt blk, int mode); + bool get_block_header(ton::BlockIdExt blk, int mode, td::Promise promise); + bool lookup_show_block(ton::ShardIdFull shard, int mode, td::uint64 arg); + bool lookup_block(ton::ShardIdFull shard, int mode, td::uint64 arg, td::Promise); + void got_block_header_raw(td::BufferSlice res, td::Promise promise, ton::BlockIdExt req_blkid = {}); void got_block_header(ton::BlockIdExt blkid, td::BufferSlice data, int mode); bool show_block_header(ton::BlockIdExt blkid, Ref root, int mode); bool show_state_header(ton::BlockIdExt blkid, Ref root, int mode); @@ -177,9 +252,28 @@ class TestNode : public td::actor::Actor { void got_block_proof(ton::BlockIdExt from, ton::BlockIdExt to, int mode, td::BufferSlice res); bool get_creator_stats(ton::BlockIdExt blkid, int mode, unsigned req_count, ton::Bits256 start_after, ton::UnixTime min_utime); - void got_creator_stats(ton::BlockIdExt req_blkid, ton::BlockIdExt blkid, int req_mode, int mode, - td::Bits256 start_after, ton::UnixTime min_utime, td::BufferSlice state_proof, - td::BufferSlice data_proof, int count, int req_count, bool complete); + bool get_creator_stats(ton::BlockIdExt blkid, int mode, unsigned req_count, ton::Bits256 start_after, + ton::UnixTime min_utime, creator_stats_func_t func, td::Promise promise); + bool get_creator_stats(ton::BlockIdExt blkid, unsigned req_count, ton::UnixTime min_utime, creator_stats_func_t func, + std::unique_ptr state, td::Promise> promise); + void got_creator_stats(ton::BlockIdExt req_blkid, ton::BlockIdExt blkid, int mode, ton::UnixTime min_utime, + td::BufferSlice state_proof, td::BufferSlice data_proof, int count, int req_count, + bool complete, creator_stats_func_t func, std::unique_ptr state, + td::Promise> promise); + bool check_validator_load(int start_time, int end_time, int mode = 0, std::string file_pfx = ""); + void continue_check_validator_load(ton::BlockIdExt blkid1, Ref root1, ton::BlockIdExt blkid2, + Ref root2, int mode = 0, std::string file_pfx = ""); + void continue_check_validator_load2(std::unique_ptr info1, + std::unique_ptr info2, int mode = 0, + std::string file_pfx = ""); + void continue_check_validator_load3(std::unique_ptr info1, + std::unique_ptr info2, int mode = 0, + std::string file_pfx = ""); + td::Status write_val_create_proof(ValidatorLoadInfo& info1, ValidatorLoadInfo& info2, int idx, bool severe, + std::string file_pfx, int cnt); + bool load_creator_stats(std::unique_ptr load_to, + td::Promise> promise, bool need_proofs); + td::Status check_validator_load_proof(std::string filename); bool cache_cell(Ref cell); bool list_cached_cells() const; bool dump_cached_cell(td::Slice hash_pfx, td::Slice type_name = {}); @@ -222,6 +316,17 @@ class TestNode : public td::actor::Actor { bool show_new_blkids(bool all = false); bool complete_blkid(ton::BlockId partial_blkid, ton::BlockIdExt& complete_blkid) const; td::Promise trivial_promise(); + template + td::Promise trivial_promise_of() { + return td::PromiseCreator::lambda([Self = actor_id(this)](td::Result res) { + if (res.is_error()) { + LOG(ERROR) << "error: " << res.move_as_error(); + } + }); + } + static ton::UnixTime now() { + return static_cast(td::Clocks::system()); + } static const tlb::TypenameLookup& get_tlb_dict(); public: @@ -292,7 +397,8 @@ class TestNode : public td::actor::Actor { //td::actor::SchedulerContext::get()->stop(); } - void got_result(); + void got_result(td::Result R, td::Promise promise); + void after_got_result(bool ok); bool envelope_send_query(td::BufferSlice query, td::Promise promise); void parse_line(td::BufferSlice data); diff --git a/submodules/ton/tonlib-src/tdactor/td/actor/PromiseFuture.h b/submodules/ton/tonlib-src/tdactor/td/actor/PromiseFuture.h index 022a98e32f3..2b8890d3f2a 100644 --- a/submodules/ton/tonlib-src/tdactor/td/actor/PromiseFuture.h +++ b/submodules/ton/tonlib-src/tdactor/td/actor/PromiseFuture.h @@ -44,8 +44,24 @@ class GetArg { using type = Arg; }; +template +struct GetRet : public GetRet {}; + +template +class GetRet { + public: + using type = R; +}; +template +class GetRet { + public: + using type = R; +}; + template using get_arg_t = std::decay_t::type>; +template +using get_ret_t = std::decay_t::type>; template struct DropResult { @@ -131,6 +147,7 @@ constexpr bool is_promise_interface_ptr() { template class LambdaPromise : public PromiseInterface { public: + using ArgT = ValueT; void set_value(ValueT &&value) override { CHECK(has_lambda_.get()); do_ok(std::move(value)); @@ -288,12 +305,6 @@ class Promise { std::unique_ptr> promise_; }; -template -auto make_promise(F &&f) { - using ValueT = detail::drop_result_t>; - return Promise(promise_interface_ptr(std::forward(f))); -} - namespace detail { template class JoinPromise : public PromiseInterface { @@ -331,6 +342,16 @@ class PromiseCreator { } }; +template +auto make_promise(F &&f) { + using ValueT = typename decltype(PromiseCreator::lambda(std::move(f)))::ArgT; + return Promise(PromiseCreator::lambda(std::move(f))); +} +template +auto make_promise(Promise &&f) { + return std::move(f); +} + template class SafePromise { public: @@ -356,4 +377,145 @@ class SafePromise { Promise promise_; Result result_; }; + +template +class PromiseMerger; + +template +struct SplitPromise { + using PromiseT = decltype(make_promise(std::declval())); + using ArgT = typename PromiseT::ArgT; + + template + static std::pair, Promise> split(std::pair); + template + static std::tuple...> split(std::tuple); + using SplittedT = decltype(split(std::declval())); + + template + static PromiseMerger merger(std::pair); + template + static PromiseMerger merger(std::tuple); + using MergerT = decltype(merger(std::declval())); +}; + +template +class PromiseMerger : public std::enable_shared_from_this> { + public: + std::tuple...> args_; + PromiseT promise_; + + PromiseMerger(PromiseT promise) : promise_(std::move(promise)) { + } + ~PromiseMerger() { + td::Status status; + tuple_for_each(args_, [&status](auto &&arg) { + if (status.is_error()) { + return; + } + if (arg.is_error()) { + status = arg.move_as_error(); + } + }); + if (status.is_error()) { + promise_.set_error(std::move(status)); + return; + } + call_tuple([this](auto &&... args) { promise_.set_value({args.move_as_ok()...}); }, std::move(args_)); + } + + template + Promise make_promise(T &arg) { + return [&arg, self = this->shared_from_this()](auto res) { arg = std::move(res); }; + } + + template + auto split() { + return call_tuple([this](auto &&... arg) { return R{this->make_promise(arg)...}; }, std::move(args_)); + } +}; + +template +auto split_promise(F &&f) { + auto merger = std::make_shared::MergerT>(std::move(f)); + return merger->template split::SplittedT>(); +} + +template +struct PromiseFuture { + Result> promise_; + Result result_; + ~PromiseFuture() { + if (promise_.is_ok()) { + promise_.move_as_ok().set_result(std::move(result_)); + } else { + LOG(ERROR) << "Lost PromiseFuture"; + } + } +}; +template +struct Future; + +template +std::pair, Future> make_promise_future(); + +template +struct Future { + Promise> promise_; + Future(Promise> promise) : promise_(std::move(promise)) { + } + + void finish(Promise promise) { + promise_.set_value(std::move(promise)); + } + + template + auto map(F &&f) { + using R = detail::drop_result_t()))>; + auto pf = make_promise_future(); + promise_.set_value([p = std::move(pf.first), f = std::move(f)](Result res) mutable { + TRY_RESULT_PROMISE(p, x, std::move(res)); + p.set_result(f(std::move(x))); + }); + + return std::move(pf.second); + } + + template + auto fmap(F &&f) { + return flatten(map(std::move(f))); + } + + template + static Future flatten(Future> ff) { + auto pf = make_promise_future(); + ff.promise_.set_value([p = std::move(pf.first)](Result> r_f) mutable { + TRY_RESULT_PROMISE(p, f, std::move(r_f)); + // Promise p + // Future f + f.promise_.set_value(std::move(p)); + }); + return std::move(pf.second); + } +}; + +template +Future make_future(T &&value) { + return Future([value = std::move(value)](Result> r_promise) mutable { + if (r_promise.is_ok()) { + r_promise.move_as_ok().set_value(std::move(value)); + } else { + LOG(ERROR) << "Lost future"; + } + }); +} + +template +std::pair, Future> make_promise_future() { + auto pf = std::make_shared>(); + Future future([pf](Result> res) mutable { pf->promise_ = std::move(res); }); + Promise promise = [pf = std::move(pf)](Result res) mutable { pf->result_ = std::move(res); }; + return std::make_pair(std::move(promise), std::move(future)); +} + } // namespace td diff --git a/submodules/ton/tonlib-src/tdactor/td/actor/actor.h b/submodules/ton/tonlib-src/tdactor/td/actor/actor.h index 5f6995887cf..1f4f6e9941c 100644 --- a/submodules/ton/tonlib-src/tdactor/td/actor/actor.h +++ b/submodules/ton/tonlib-src/tdactor/td/actor/actor.h @@ -100,6 +100,28 @@ void send_closure(ActorIdT &&actor_id, FunctionT function, ArgsT &&... args) { #endif +template , + size_t argument_count = member_function_argument_count(), + std::enable_if_t with_promise = false> +auto future_send_closure(ActorIdT &&actor_id, FunctionT function, ArgsT &&... args) { + using R = ::td::detail::get_ret_t>; + auto pf = make_promise_future(); + send_closure(std::forward(actor_id), std::move(function), std::forward(args)..., + std::move(pf.first)); + return std::move(pf.second); +} + +template , + size_t argument_count = member_function_argument_count(), + std::enable_if_t with_promise = true> +Future future_send_closure(ActorIdT &&actor_id, FunctionT function, ArgsT &&... args) { + auto pf = make_promise_future(); + send_closure(std::forward(actor_id), std::move(function), std::forward(args)..., + std::move(pf.first)); + return std::move(pf.second); +} + template bool send_closure_bool(ActorIdT &&actor_id, FunctionT function, ArgsT &&... args) { send_closure(std::forward(actor_id), function, std::forward(args)...); diff --git a/submodules/ton/tonlib-src/tdactor/td/actor/common.h b/submodules/ton/tonlib-src/tdactor/td/actor/common.h index 33e259a2765..eacc6192d0c 100644 --- a/submodules/ton/tonlib-src/tdactor/td/actor/common.h +++ b/submodules/ton/tonlib-src/tdactor/td/actor/common.h @@ -63,6 +63,36 @@ class ActorSignals { using core::Actor; using core::SchedulerContext; using core::SchedulerId; +using core::set_debug; + +struct Debug { + public: + Debug() = default; + Debug(std::shared_ptr group_info) : group_info_(std::move(group_info)) { + } + template + void for_each(F &&f) { + for (auto &scheduler : group_info_->schedulers) { + f(scheduler.io_worker->debug); + for (auto &cpu : scheduler.cpu_workers) { + f(cpu->debug); + } + } + } + + void dump() { + for_each([](core::Debug &debug) { + core::DebugInfo info; + debug.read(info); + if (info.is_active) { + LOG(ERROR) << info.name << " " << td::format::as_time(Time::now() - info.start_at); + } + }); + } + + private: + std::shared_ptr group_info_; +}; class Scheduler { public: @@ -110,6 +140,10 @@ class Scheduler { } } + Debug get_debug() { + return Debug{group_info_}; + } + bool run() { start(); while (schedulers_[0]->run(10)) { diff --git a/submodules/ton/tonlib-src/tdactor/td/actor/core/CpuWorker.cpp b/submodules/ton/tonlib-src/tdactor/td/actor/core/CpuWorker.cpp index d752560ddc3..d78660c6fc4 100644 --- a/submodules/ton/tonlib-src/tdactor/td/actor/core/CpuWorker.cpp +++ b/submodules/ton/tonlib-src/tdactor/td/actor/core/CpuWorker.cpp @@ -32,6 +32,7 @@ void CpuWorker::run() { MpmcWaiter::Slot slot; waiter_.init_slot(slot, thread_id); + auto &debug = dispatcher.get_debug(); while (true) { SchedulerMessage message; if (try_pop(message, thread_id)) { @@ -39,6 +40,7 @@ void CpuWorker::run() { if (!message) { return; } + auto lock = debug.start(message->get_name()); ActorExecutor executor(*message, dispatcher, ActorExecutor::Options().with_from_queue()); } else { waiter_.wait(slot); diff --git a/submodules/ton/tonlib-src/tdactor/td/actor/core/IoWorker.cpp b/submodules/ton/tonlib-src/tdactor/td/actor/core/IoWorker.cpp index d1f10c63341..ee3576bdf5d 100644 --- a/submodules/ton/tonlib-src/tdactor/td/actor/core/IoWorker.cpp +++ b/submodules/ton/tonlib-src/tdactor/td/actor/core/IoWorker.cpp @@ -19,6 +19,7 @@ #include "td/actor/core/IoWorker.h" #include "td/actor/core/ActorExecutor.h" +#include "td/actor/core/Scheduler.h" namespace td { namespace actor { @@ -42,6 +43,7 @@ bool IoWorker::run_once(double timeout) { auto &poll = SchedulerContext::get()->get_poll(); #endif auto &heap = SchedulerContext::get()->get_heap(); + auto &debug = SchedulerContext::get()->get_debug(); auto now = Time::now(); // update Time::now_cached() while (!heap.empty() && heap.top_key() <= now) { @@ -49,6 +51,7 @@ bool IoWorker::run_once(double timeout) { auto *actor_info = ActorInfo::from_heap_node(heap_node); auto id = actor_info->unpin(); + auto lock = debug.start(actor_info->get_name()); ActorExecutor executor(*actor_info, dispatcher, ActorExecutor::Options().with_has_poll(true)); if (executor.can_send_immediate()) { executor.send_immediate(ActorSignals::one(ActorSignals::Alarm)); @@ -68,6 +71,7 @@ bool IoWorker::run_once(double timeout) { dispatcher.set_alarm_timestamp(message); continue; } + auto lock = debug.start(message->get_name()); ActorExecutor executor(*message, dispatcher, ActorExecutor::Options().with_from_queue().with_has_poll(true)); } queue_.reader_flush(); diff --git a/submodules/ton/tonlib-src/tdactor/td/actor/core/Scheduler.cpp b/submodules/ton/tonlib-src/tdactor/td/actor/core/Scheduler.cpp index 0863bda0d1c..f79620d9f38 100644 --- a/submodules/ton/tonlib-src/tdactor/td/actor/core/Scheduler.cpp +++ b/submodules/ton/tonlib-src/tdactor/td/actor/core/Scheduler.cpp @@ -25,6 +25,15 @@ namespace td { namespace actor { namespace core { +std::atomic debug; +void set_debug(bool flag) { + debug = flag; +} + +bool need_debug() { + return debug.load(std::memory_order_relaxed); +} + Scheduler::Scheduler(std::shared_ptr scheduler_group_info, SchedulerId id, size_t cpu_threads_count) : scheduler_group_info_(std::move(scheduler_group_info)), cpu_threads_(cpu_threads_count) { scheduler_group_info_->active_scheduler_count++; @@ -128,13 +137,14 @@ void Scheduler::do_stop() { } Scheduler::ContextImpl::ContextImpl(ActorInfoCreator *creator, SchedulerId scheduler_id, CpuWorkerId cpu_worker_id, - SchedulerGroupInfo *scheduler_group, Poll *poll, KHeap *heap) + SchedulerGroupInfo *scheduler_group, Poll *poll, KHeap *heap, Debug *debug) : creator_(creator) , scheduler_id_(scheduler_id) , cpu_worker_id_(cpu_worker_id) , scheduler_group_(scheduler_group) , poll_(poll) - , heap_(heap) { + , heap_(heap) + , debug_(debug) { } SchedulerId Scheduler::ContextImpl::get_scheduler_id() const { @@ -184,6 +194,9 @@ KHeap &Scheduler::ContextImpl::get_heap() { CHECK(has_heap()); return *heap_; } +Debug &Scheduler::ContextImpl::get_debug() { + return *debug_; +} void Scheduler::ContextImpl::set_alarm_timestamp(const ActorInfoPtr &actor_info_ptr) { // Ideas for optimization diff --git a/submodules/ton/tonlib-src/tdactor/td/actor/core/Scheduler.h b/submodules/ton/tonlib-src/tdactor/td/actor/core/Scheduler.h index 3cc627ee454..377d835f190 100644 --- a/submodules/ton/tonlib-src/tdactor/td/actor/core/Scheduler.h +++ b/submodules/ton/tonlib-src/tdactor/td/actor/core/Scheduler.h @@ -31,6 +31,7 @@ #include "td/actor/core/SchedulerId.h" #include "td/actor/core/SchedulerMessage.h" +#include "td/utils/AtomicRead.h" #include "td/utils/Closure.h" #include "td/utils/common.h" #include "td/utils/format.h" @@ -65,6 +66,54 @@ namespace actor { namespace core { class IoWorker; +struct DebugInfo { + bool is_active{false}; + double start_at{0}; + static constexpr size_t name_size{32}; + char name[name_size] = {}; + void set_name(td::Slice from) { + from.truncate(name_size - 1); + std::memcpy(name, from.data(), from.size()); + name[from.size()] = 0; + } +}; + +void set_debug(bool flag); +bool need_debug(); + +struct Debug { + public: + bool is_on() const { + return need_debug(); + } + struct Destructor { + void operator()(Debug *info) { + info->info_.lock().value().is_active = false; + } + }; + + void read(DebugInfo &info) { + info_.read(info); + } + + std::unique_ptr start(td::Slice name) { + if (!is_on()) { + return {}; + } + { + auto lock = info_.lock(); + auto &value = lock.value(); + value.is_active = true; + value.start_at = Time::now(); + value.set_name(name); + } + return std::unique_ptr(this); + } + + private: + AtomicRead info_; +}; + struct WorkerInfo { enum class Type { Io, Cpu } type{Type::Io}; WorkerInfo() = default; @@ -73,6 +122,7 @@ struct WorkerInfo { } ActorInfoCreator actor_info_creator; CpuWorkerId cpu_worker_id; + Debug debug; }; template @@ -195,7 +245,7 @@ class Scheduler { class ContextImpl : public SchedulerContext { public: ContextImpl(ActorInfoCreator *creator, SchedulerId scheduler_id, CpuWorkerId cpu_worker_id, - SchedulerGroupInfo *scheduler_group, Poll *poll, KHeap *heap); + SchedulerGroupInfo *scheduler_group, Poll *poll, KHeap *heap, Debug *debug); SchedulerId get_scheduler_id() const override; void add_to_queue(ActorInfoPtr actor_info_ptr, SchedulerId scheduler_id, bool need_poll) override; @@ -208,6 +258,8 @@ class Scheduler { bool has_heap() override; KHeap &get_heap() override; + Debug &get_debug() override; + void set_alarm_timestamp(const ActorInfoPtr &actor_info_ptr) override; bool is_stop_requested() override; @@ -225,6 +277,8 @@ class Scheduler { Poll *poll_; KHeap *heap_; + + Debug *debug_; }; template @@ -234,7 +288,8 @@ class Scheduler { #endif bool is_io_worker = worker_info.type == WorkerInfo::Type::Io; ContextImpl context(&worker_info.actor_info_creator, info_->id, worker_info.cpu_worker_id, - scheduler_group_info_.get(), is_io_worker ? &poll_ : nullptr, is_io_worker ? &heap_ : nullptr); + scheduler_group_info_.get(), is_io_worker ? &poll_ : nullptr, is_io_worker ? &heap_ : nullptr, + &worker_info.debug); SchedulerContext::Guard guard(&context); f(); } diff --git a/submodules/ton/tonlib-src/tdactor/td/actor/core/SchedulerContext.h b/submodules/ton/tonlib-src/tdactor/td/actor/core/SchedulerContext.h index 49cbf63d0f8..e46aef7d59e 100644 --- a/submodules/ton/tonlib-src/tdactor/td/actor/core/SchedulerContext.h +++ b/submodules/ton/tonlib-src/tdactor/td/actor/core/SchedulerContext.h @@ -37,6 +37,7 @@ class SchedulerDispatcher { virtual void set_alarm_timestamp(const ActorInfoPtr &actor_info_ptr) = 0; }; +struct Debug; class SchedulerContext : public Context, public SchedulerDispatcher { public: virtual ~SchedulerContext() = default; @@ -55,6 +56,9 @@ class SchedulerContext : public Context, public SchedulerDispa // Stop all schedulers virtual bool is_stop_requested() = 0; virtual void stop() = 0; + + // Debug + virtual Debug &get_debug() = 0; }; } // namespace core } // namespace actor diff --git a/submodules/ton/tonlib-src/tdactor/test/actors_core.cpp b/submodules/ton/tonlib-src/tdactor/test/actors_core.cpp index 1ec9dda249e..ae10eb9bebd 100644 --- a/submodules/ton/tonlib-src/tdactor/test/actors_core.cpp +++ b/submodules/ton/tonlib-src/tdactor/test/actors_core.cpp @@ -675,7 +675,8 @@ TEST(Actor2, actor_function_result) { public: A(std::shared_ptr watcher) : watcher_(std::move(watcher)) { } - void on_result(uint32 x, uint32 y) { + void on_result(uint32 x, td::Result r_y) { + auto y = r_y.move_as_ok(); LOG_CHECK(x * x == y) << x << " " << y; if (--cnt_ == 0) { stop(); @@ -683,7 +684,7 @@ TEST(Actor2, actor_function_result) { } void start_up() { b_ = create_actor(ActorOptions().with_name("B")); - cnt_ = 3; + cnt_ = 5; send_closure(b_, &B::query, 3, [a = std::make_unique(), self = actor_id(this)](td::Result y) { LOG_IF(ERROR, y.is_error()) << y.error(); send_closure(self, &A::on_result, 3, y.ok()); @@ -696,6 +697,11 @@ TEST(Actor2, actor_function_result) { CHECK(!self.empty()); send_closure(self, &A::on_result, 5, y); }); + auto future = future_send_closure(b_, &B::query, 7); + future.finish(td::promise_send_closure(actor_id(this), &A::on_result, 7)); + //TODO: deduce Future type (i.e. Future) + auto future2 = future_send_closure(b_, &B::query_async, 7); + future2.finish(td::promise_send_closure(actor_id(this), &A::on_result, 7)); } private: @@ -714,12 +720,12 @@ TEST(Actor2, actor_function_result) { } TEST(Actor2, actor_ping_pong) { - auto group_info = std::make_shared(1); - core::Scheduler scheduler{group_info, SchedulerId{0}, 3}; + Scheduler scheduler{{3}, Scheduler::Paused}; sb.clear(); scheduler.start(); auto watcher = td::create_shared_destructor([] { SchedulerContext::get()->stop(); }); + td::actor::set_debug(true); for (int i = 0; i < 2000; i++) { scheduler.run_in_context([watcher] { class PingPong : public Actor { @@ -781,9 +787,9 @@ TEST(Actor2, actor_ping_pong) { }); } watcher.reset(); - while (scheduler.run(1000)) { + while (scheduler.run(0.1)) { + //scheduler.get_debug().dump(); } - core::Scheduler::close_scheduler_group(*group_info); sb.clear(); } diff --git a/submodules/ton/tonlib-src/tdactor/test/actors_promise.cpp b/submodules/ton/tonlib-src/tdactor/test/actors_promise.cpp index 5921f725f1e..f1d57069763 100644 --- a/submodules/ton/tonlib-src/tdactor/test/actors_promise.cpp +++ b/submodules/ton/tonlib-src/tdactor/test/actors_promise.cpp @@ -135,6 +135,78 @@ TEST(Actor, safe_promise) { ASSERT_EQ(res, 3); } +TEST(Actor, split_promise) { + using td::Promise; + using td::Result; + using td::split_promise; + using td::SplitPromise; + { + td::optional> x; + auto pair = [&](Result> res) { x = res.move_as_ok(); }; + static_assert(std::is_same::ArgT, std::pair>::value, "A"); + static_assert( + std::is_same::SplittedT, std::pair, Promise>>::value, "A"); + auto splitted = split_promise(pair); + static_assert(std::is_same, Promise>>::value, "A"); + + splitted.first.set_value(1); + splitted.second.set_value(2.0); + CHECK(x.unwrap() == std::make_pair(1, 2.0)); + } // namespace td + { + td::optional> x; + auto triple = [&](Result> res) { x = res.move_as_ok(); }; + static_assert(std::is_same::ArgT, std::tuple>::value, "A"); + static_assert(std::is_same::SplittedT, + std::tuple, Promise, Promise>>::value, + "A"); + auto splitted = split_promise(triple); + static_assert( + std::is_same, Promise, Promise>>::value, "A"); + std::get<0>(splitted).set_value(1); + std::get<1>(splitted).set_value(2.0); + std::get<2>(splitted).set_value("hello"); + CHECK(x.unwrap() == std::make_tuple(1, 2.0, "hello")); + } + { + int code = 0; + auto pair = [&](Result> res) { + res.ensure_error(); + code = res.error().code(); + }; + auto splitted = split_promise(td::Promise>(pair)); + splitted.second.set_error(td::Status::Error(123, "123")); + CHECK(code == 0); + splitted.first.set_value(1); + CHECK(code == 123); + } +} + +TEST(Actor, promise_future) { + using td::make_promise_future; + { + auto pf = make_promise_future(); + td::optional res; + pf.second.map([](int x) { return x * 2; }).map([](int x) { return x + 10; }).map([&](int x) { + res = x; + return td::Unit(); + }); + CHECK(!res); + pf.first.set_value(6); + ASSERT_EQ(22, res.unwrap()); + } + { + LOG(ERROR) << "Second test"; + td::optional res; + td::make_future(6) + .map([](int x) { return x * 2; }) + .map([](int x) { return x + 10; }) + .fmap([&](int x) { return td::make_future(x * 2); }) + .finish([&](int x) { res = x; }); + ASSERT_EQ(44, res.unwrap()); + } +} + TEST(Actor2, actor_lost_promise) { using namespace td::actor; using namespace td; @@ -459,7 +531,7 @@ class SampleActor : public Actor { detail::current_actor().print_a(); co_await OnActor(self); LOG(ERROR) << "exit print_a"; - co_return{}; + co_return {}; } task print_b() { auto self = actor_id(this); @@ -468,7 +540,7 @@ class SampleActor : public Actor { detail::current_actor().print_b(); co_await OnActor(self); LOG(ERROR) << "exit print_b"; - co_return{}; + co_return {}; } immediate_task run_coroutine() { diff --git a/submodules/ton/tonlib-src/tddb/td/db/KeyValue.h b/submodules/ton/tonlib-src/tddb/td/db/KeyValue.h index 088958f6bb8..4e0d853849b 100644 --- a/submodules/ton/tonlib-src/tddb/td/db/KeyValue.h +++ b/submodules/ton/tonlib-src/tddb/td/db/KeyValue.h @@ -55,6 +55,10 @@ class KeyValue : public KeyValueReader { virtual Status set(Slice key, Slice value) = 0; virtual Status erase(Slice key) = 0; + virtual Status begin_write_batch() = 0; + virtual Status commit_write_batch() = 0; + virtual Status abort_write_batch() = 0; + virtual Status begin_transaction() = 0; virtual Status commit_transaction() = 0; virtual Status abort_transaction() = 0; @@ -86,6 +90,16 @@ class PrefixedKeyValue : public KeyValue { return kv_->erase(PSLICE() << prefix_ << key); } + Status begin_write_batch() override { + return kv_->begin_write_batch(); + } + Status commit_write_batch() override { + return kv_->commit_write_batch(); + } + Status abort_write_batch() override { + return kv_->abort_write_batch(); + } + Status begin_transaction() override { return kv_->begin_transaction(); } diff --git a/submodules/ton/tonlib-src/tddb/td/db/MemoryKeyValue.cpp b/submodules/ton/tonlib-src/tddb/td/db/MemoryKeyValue.cpp index 473ee780069..aaf5472d734 100644 --- a/submodules/ton/tonlib-src/tddb/td/db/MemoryKeyValue.cpp +++ b/submodules/ton/tonlib-src/tddb/td/db/MemoryKeyValue.cpp @@ -61,6 +61,15 @@ std::unique_ptr MemoryKeyValue::snapshot() { std::string MemoryKeyValue::stats() const { return PSTRING() << "MemoryKeyValueStats{" << tag("get_count", get_count_) << "}"; } +Status MemoryKeyValue::begin_write_batch() { + UNREACHABLE(); +} +Status MemoryKeyValue::commit_write_batch() { + UNREACHABLE(); +} +Status MemoryKeyValue::abort_write_batch() { + UNREACHABLE(); +} Status MemoryKeyValue::begin_transaction() { UNREACHABLE(); diff --git a/submodules/ton/tonlib-src/tddb/td/db/MemoryKeyValue.h b/submodules/ton/tonlib-src/tddb/td/db/MemoryKeyValue.h index ee6fd36df3c..c9d584bcfde 100644 --- a/submodules/ton/tonlib-src/tddb/td/db/MemoryKeyValue.h +++ b/submodules/ton/tonlib-src/tddb/td/db/MemoryKeyValue.h @@ -29,6 +29,10 @@ class MemoryKeyValue : public KeyValue { Status erase(Slice key) override; Result count(Slice prefix) override; + Status begin_write_batch() override; + Status commit_write_batch() override; + Status abort_write_batch() override; + Status begin_transaction() override; Status commit_transaction() override; Status abort_transaction() override; diff --git a/submodules/ton/tonlib-src/tddb/td/db/RocksDb.cpp b/submodules/ton/tonlib-src/tddb/td/db/RocksDb.cpp index e99cd43617f..500985e2d53 100644 --- a/submodules/ton/tonlib-src/tddb/td/db/RocksDb.cpp +++ b/submodules/ton/tonlib-src/tddb/td/db/RocksDb.cpp @@ -78,7 +78,18 @@ Result RocksDb::open(std::string path) { options.bytes_per_sync = 1 << 20; options.writable_file_max_buffer_size = 2 << 14; options.statistics = statistics; - TRY_STATUS(from_rocksdb(rocksdb::OptimisticTransactionDB::Open(options, std::move(path), &db))); + rocksdb::OptimisticTransactionDBOptions occ_options; + occ_options.validate_policy = rocksdb::OccValidationPolicy::kValidateSerial; + rocksdb::ColumnFamilyOptions cf_options(options); + std::vector column_families; + column_families.push_back(rocksdb::ColumnFamilyDescriptor(rocksdb::kDefaultColumnFamilyName, cf_options)); + std::vector handles; + TRY_STATUS(from_rocksdb( + rocksdb::OptimisticTransactionDB::Open(options, occ_options, std::move(path), column_families, &handles, &db))); + CHECK(handles.size() == 1); + // i can delete the handle since DBImpl is always holding a reference to + // default column family + delete handles[0]; } return RocksDb(std::shared_ptr(db), std::move(statistics)); } @@ -161,31 +172,41 @@ Result RocksDb::count(Slice prefix) { return res; } +Status RocksDb::begin_write_batch() { + CHECK(!transaction_); + write_batch_ = std::make_unique(); + return Status::OK(); +} + Status RocksDb::begin_transaction() { - //write_batch_ = std::make_unique(); + CHECK(!write_batch_); rocksdb::WriteOptions options; options.sync = true; transaction_.reset(db_->BeginTransaction(options, {})); return Status::OK(); } -Status RocksDb::commit_transaction() { - //CHECK(write_batch_); - //auto write_batch = std::move(write_batch_); - //rocksdb::WriteOptions options; - //options.sync = true; - //TRY_STATUS(from_rocksdb(db_->Write(options, write_batch.get()))); - //return Status::OK(); +Status RocksDb::commit_write_batch() { + CHECK(write_batch_); + auto write_batch = std::move(write_batch_); + rocksdb::WriteOptions options; + options.sync = true; + return from_rocksdb(db_->Write(options, write_batch.get())); +} +Status RocksDb::commit_transaction() { CHECK(transaction_); - auto res = from_rocksdb(transaction_->Commit()); - transaction_.reset(); - return res; + auto transaction = std::move(transaction_); + return from_rocksdb(transaction->Commit()); +} + +Status RocksDb::abort_write_batch() { + CHECK(write_batch_); + write_batch_.reset(); + return Status::OK(); } Status RocksDb::abort_transaction() { - //CHECK(write_batch_); - //write_batch_.reset(); CHECK(transaction_); transaction_.reset(); return Status::OK(); diff --git a/submodules/ton/tonlib-src/tddb/td/db/RocksDb.h b/submodules/ton/tonlib-src/tddb/td/db/RocksDb.h index 3745701b26b..b8bfaf9da6a 100644 --- a/submodules/ton/tonlib-src/tddb/td/db/RocksDb.h +++ b/submodules/ton/tonlib-src/tddb/td/db/RocksDb.h @@ -45,6 +45,10 @@ class RocksDb : public KeyValue { Status erase(Slice key) override; Result count(Slice prefix) override; + Status begin_write_batch() override; + Status commit_write_batch() override; + Status abort_write_batch() override; + Status begin_transaction() override; Status commit_transaction() override; Status abort_transaction() override; diff --git a/submodules/ton/tonlib-src/tdutils/generate/auto/extension_to_mime_type.cpp b/submodules/ton/tonlib-src/tdutils/generate/auto/extension_to_mime_type.cpp new file mode 100644 index 00000000000..a0ba68500a1 --- /dev/null +++ b/submodules/ton/tonlib-src/tdutils/generate/auto/extension_to_mime_type.cpp @@ -0,0 +1,3196 @@ +/* ANSI-C code produced by gperf version 3.0.3 */ +/* Command-line: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/gperf -m100 auto/extension_to_mime_type.gperf */ +/* Computed positions: -k'1-4,6,$' */ + +#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \ + && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \ + && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \ + && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \ + && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \ + && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \ + && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \ + && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \ + && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \ + && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \ + && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \ + && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \ + && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \ + && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \ + && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \ + && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \ + && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \ + && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \ + && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \ + && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \ + && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \ + && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \ + && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126)) +/* The character set is not based on ISO-646. */ +#error "gperf generated tables don't work with this execution character set. Please report a bug to ." +#endif + +#line 12 "auto/extension_to_mime_type.gperf" +struct extension_and_mime_type { + const char *extension; + const char *mime_type; +}; +#include +/* maximum key range = 3879, duplicates = 0 */ + +#ifndef GPERF_DOWNCASE +#define GPERF_DOWNCASE 1 +static unsigned char gperf_downcase[256] = + { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, + 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, + 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, + 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, + 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, + 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, + 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, + 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, + 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, + 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, + 255 + }; +#endif + +#ifndef GPERF_CASE_STRCMP +#define GPERF_CASE_STRCMP 1 +static int +gperf_case_strcmp (register const char *s1, register const char *s2) +{ + for (;;) + { + unsigned char c1 = gperf_downcase[(unsigned char)*s1++]; + unsigned char c2 = gperf_downcase[(unsigned char)*s2++]; + if (c1 != 0 && c1 == c2) + continue; + return (int)c1 - (int)c2; + } +} +#endif + +#ifdef __GNUC__ +__inline +#else +#ifdef __cplusplus +inline +#endif +#endif +static unsigned int +extension_hash (register const char *str, register unsigned int len) +{ + static const unsigned short asso_values[] = + { + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 18, 3916, 3916, 19, 113, + 129, 700, 58, 21, 18, 20, 23, 21, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 326, 825, 38, 46, 692, + 40, 316, 979, 429, 1051, 546, 156, 19, 919, 593, + 29, 296, 157, 18, 21, 362, 95, 89, 26, 1194, + 557, 3916, 3916, 3916, 3916, 21, 18, 326, 825, 38, + 46, 692, 40, 316, 979, 429, 1051, 546, 156, 19, + 919, 593, 29, 296, 157, 18, 21, 362, 95, 89, + 26, 1194, 557, 1255, 389, 28, 622, 1358, 363, 973, + 1401, 183, 70, 1211, 216, 744, 362, 455, 698, 1759, + 18, 85, 3916, 3916, 3916, 3916, 3916, 3916, 21, 362, + 95, 89, 26, 1194, 557, 1255, 389, 28, 622, 1358, + 363, 973, 1401, 183, 70, 1211, 216, 744, 362, 455, + 698, 1759, 18, 85, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, 3916, + 3916, 3916, 3916, 3916, 3916, 3916, 3916 + }; + register unsigned int hval = len; + + switch (hval) + { + default: + hval += asso_values[(unsigned char)str[5]]; + /*FALLTHROUGH*/ + case 5: + case 4: + hval += asso_values[(unsigned char)str[3]]; + /*FALLTHROUGH*/ + case 3: + hval += asso_values[(unsigned char)str[2]]; + /*FALLTHROUGH*/ + case 2: + hval += asso_values[(unsigned char)str[1]+51]; + /*FALLTHROUGH*/ + case 1: + hval += asso_values[(unsigned char)str[0]]; + break; + } + return hval + asso_values[(unsigned char)str[len - 1]]; +} + +const struct extension_and_mime_type * +search_extension (register const char *str, register unsigned int len) +{ + enum + { + TOTAL_KEYWORDS = 981, + MIN_WORD_LENGTH = 1, + MAX_WORD_LENGTH = 11, + MIN_HASH_VALUE = 37, + MAX_HASH_VALUE = 3915 + }; + + static const struct extension_and_mime_type wordlist[] = + { + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 685 "auto/extension_to_mime_type.gperf" + {"s", "text/x-asm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 787 "auto/extension_to_mime_type.gperf" + {"t", "text/troff"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 572 "auto/extension_to_mime_type.gperf" + {"p", "text/x-pascal"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 84 "auto/extension_to_mime_type.gperf" + {"c", "text/x-c"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 240 "auto/extension_to_mime_type.gperf" + {"f", "text/x-fortran"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 581 "auto/extension_to_mime_type.gperf" + {"pas", "text/x-pascal"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 686 "auto/extension_to_mime_type.gperf" + {"s3m", "audio/s3m"}, + {"",nullptr}, {"",nullptr}, +#line 797 "auto/extension_to_mime_type.gperf" + {"tex", "application/x-tex"}, + {"",nullptr}, +#line 96 "auto/extension_to_mime_type.gperf" + {"cat", "application/vnd.ms-pki.seccat"}, + {"",nullptr}, +#line 444 "auto/extension_to_mime_type.gperf" + {"mets", "application/mets+xml"}, + {"",nullptr}, +#line 931 "auto/extension_to_mime_type.gperf" + {"xap", "application/x-silverlight-app"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 573 "auto/extension_to_mime_type.gperf" + {"p10", "application/pkcs10"}, + {"",nullptr}, {"",nullptr}, +#line 800 "auto/extension_to_mime_type.gperf" + {"text", "text/plain"}, +#line 94 "auto/extension_to_mime_type.gperf" + {"cap", "application/vnd.tcpdump.pcap"}, + {"",nullptr}, +#line 687 "auto/extension_to_mime_type.gperf" + {"saf", "application/vnd.yamaha.smaf-audio"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 426 "auto/extension_to_mime_type.gperf" + {"mads", "application/mads+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 93 "auto/extension_to_mime_type.gperf" + {"caf", "audio/x-caf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 706 "auto/extension_to_mime_type.gperf" + {"semf", "application/vnd.semf"}, + {"",nullptr}, {"",nullptr}, +#line 160 "auto/extension_to_mime_type.gperf" + {"daf", "application/vnd.mobius.daf"}, + {"",nullptr}, +#line 693 "auto/extension_to_mime_type.gperf" + {"scs", "application/scvp-cv-response"}, +#line 689 "auto/extension_to_mime_type.gperf" + {"sc", "application/vnd.ibm.secure-container"}, +#line 691 "auto/extension_to_mime_type.gperf" + {"scm", "application/vnd.lotus-screencam"}, +#line 170 "auto/extension_to_mime_type.gperf" + {"def", "text/plain"}, +#line 937 "auto/extension_to_mime_type.gperf" + {"xdm", "application/vnd.syncml.dm+xml"}, + {"",nullptr}, {"",nullptr}, +#line 705 "auto/extension_to_mime_type.gperf" + {"semd", "application/vnd.semd"}, + {"",nullptr}, +#line 924 "auto/extension_to_mime_type.gperf" + {"x3d", "model/x3d+xml"}, + {"",nullptr}, {"",nullptr}, +#line 276 "auto/extension_to_mime_type.gperf" + {"fzs", "application/vnd.fuzzysheet"}, +#line 888 "auto/extension_to_mime_type.gperf" + {"wax", "audio/x-ms-wax"}, + {"",nullptr}, {"",nullptr}, +#line 700 "auto/extension_to_mime_type.gperf" + {"sdp", "application/sdp"}, +#line 589 "auto/extension_to_mime_type.gperf" + {"pct", "image/x-pict"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 102 "auto/extension_to_mime_type.gperf" + {"cc", "text/x-c"}, +#line 246 "auto/extension_to_mime_type.gperf" + {"fcs", "application/vnd.isac.fcs"}, + {"",nullptr}, +#line 938 "auto/extension_to_mime_type.gperf" + {"xdp", "application/vnd.adobe.xdp+xml"}, + {"",nullptr}, +#line 103 "auto/extension_to_mime_type.gperf" + {"cct", "application/x-director"}, +#line 591 "auto/extension_to_mime_type.gperf" + {"pcx", "image/x-pcx"}, + {"",nullptr}, {"",nullptr}, +#line 113 "auto/extension_to_mime_type.gperf" + {"cdx", "chemical/x-cdx"}, + {"",nullptr}, +#line 415 "auto/extension_to_mime_type.gperf" + {"m14", "application/x-msmediaview"}, + {"",nullptr}, +#line 696 "auto/extension_to_mime_type.gperf" + {"sdc", "application/vnd.stardivision.calc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 939 "auto/extension_to_mime_type.gperf" + {"xdssc", "application/dssc+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 936 "auto/extension_to_mime_type.gperf" + {"xdf", "application/xcap-diff+xml"}, + {"",nullptr}, {"",nullptr}, +#line 593 "auto/extension_to_mime_type.gperf" + {"pdf", "application/pdf"}, +#line 697 "auto/extension_to_mime_type.gperf" + {"sdd", "application/vnd.stardivision.impress"}, + {"",nullptr}, {"",nullptr}, +#line 886 "auto/extension_to_mime_type.gperf" + {"wad", "application/x-doom"}, + {"",nullptr}, +#line 586 "auto/extension_to_mime_type.gperf" + {"pcf", "application/x-font-pcf"}, +#line 690 "auto/extension_to_mime_type.gperf" + {"scd", "application/x-msschedule"}, +#line 436 "auto/extension_to_mime_type.gperf" + {"mcd", "application/vnd.mcd"}, +#line 106 "auto/extension_to_mime_type.gperf" + {"cdf", "application/x-netcdf"}, + {"",nullptr}, +#line 247 "auto/extension_to_mime_type.gperf" + {"fdf", "application/vnd.fdf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 655 "auto/extension_to_mime_type.gperf" + {"ras", "image/x-cmu-raster"}, + {"",nullptr}, +#line 653 "auto/extension_to_mime_type.gperf" + {"ram", "audio/x-pn-realaudio"}, + {"",nullptr}, +#line 399 "auto/extension_to_mime_type.gperf" + {"les", "application/vnd.hhe.lesson-player"}, +#line 660 "auto/extension_to_mime_type.gperf" + {"res", "application/x-dtbresource+xml"}, + {"",nullptr}, +#line 885 "auto/extension_to_mime_type.gperf" + {"w3d", "application/x-director"}, +#line 892 "auto/extension_to_mime_type.gperf" + {"wcm", "application/vnd.ms-works"}, + {"",nullptr}, +#line 245 "auto/extension_to_mime_type.gperf" + {"fcdt", "application/vnd.adobe.formscentral.fcdt"}, + {"",nullptr}, +#line 870 "auto/extension_to_mime_type.gperf" + {"vcs", "text/x-vcalendar"}, +#line 168 "auto/extension_to_mime_type.gperf" + {"ddd", "application/vnd.fujixerox.ddd"}, +#line 582 "auto/extension_to_mime_type.gperf" + {"paw", "application/vnd.pawaafile"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 243 "auto/extension_to_mime_type.gperf" + {"f90", "text/x-fortran"}, + {"",nullptr}, +#line 894 "auto/extension_to_mime_type.gperf" + {"wdp", "image/vnd.ms-photo"}, +#line 640 "auto/extension_to_mime_type.gperf" + {"pyv", "video/vnd.ms-playready.media.pyv"}, + {"",nullptr}, {"",nullptr}, +#line 485 "auto/extension_to_mime_type.gperf" + {"mpm", "application/vnd.blueice.multipass"}, +#line 659 "auto/extension_to_mime_type.gperf" + {"rep", "application/vnd.businessobjects"}, +#line 871 "auto/extension_to_mime_type.gperf" + {"vcx", "application/vnd.vcx"}, + {"",nullptr}, +#line 488 "auto/extension_to_mime_type.gperf" + {"mpt", "application/vnd.ms-project"}, +#line 970 "auto/extension_to_mime_type.gperf" + {"xps", "application/vnd.ms-xpsdocument"}, +#line 810 "auto/extension_to_mime_type.gperf" + {"tpt", "application/vnd.trid.tpt"}, +#line 968 "auto/extension_to_mime_type.gperf" + {"xpm", "image/x-xpixmap"}, +#line 620 "auto/extension_to_mime_type.gperf" + {"pps", "application/vnd.ms-powerpoint"}, + {"",nullptr}, +#line 619 "auto/extension_to_mime_type.gperf" + {"ppm", "image/x-portable-pixmap"}, +#line 916 "auto/extension_to_mime_type.gperf" + {"wqd", "application/vnd.wqd"}, +#line 493 "auto/extension_to_mime_type.gperf" + {"ms", "text/troff"}, +#line 750 "auto/extension_to_mime_type.gperf" + {"spx", "audio/ogg"}, +#line 623 "auto/extension_to_mime_type.gperf" + {"ppt", "application/vnd.ms-powerpoint"}, +#line 416 "auto/extension_to_mime_type.gperf" + {"m1v", "video/mpeg"}, + {"",nullptr}, +#line 193 "auto/extension_to_mime_type.gperf" + {"dp", "application/vnd.osgi.dp"}, + {"",nullptr}, +#line 748 "auto/extension_to_mime_type.gperf" + {"spp", "application/scvp-vp-response"}, +#line 487 "auto/extension_to_mime_type.gperf" + {"mpp", "application/vnd.ms-project"}, +#line 972 "auto/extension_to_mime_type.gperf" + {"xpx", "application/vnd.intercon.formnet"}, +#line 630 "auto/extension_to_mime_type.gperf" + {"ps", "application/postscript"}, +#line 143 "auto/extension_to_mime_type.gperf" + {"cpt", "application/mac-compactpro"}, +#line 180 "auto/extension_to_mime_type.gperf" + {"djv", "image/vnd.djvu"}, + {"",nullptr}, {"",nullptr}, +#line 161 "auto/extension_to_mime_type.gperf" + {"dart", "application/vnd.dart"}, + {"",nullptr}, +#line 621 "auto/extension_to_mime_type.gperf" + {"ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12"}, +#line 868 "auto/extension_to_mime_type.gperf" + {"vcf", "text/x-vcard"}, + {"",nullptr}, +#line 624 "auto/extension_to_mime_type.gperf" + {"pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12"}, + {"",nullptr}, {"",nullptr}, +#line 267 "auto/extension_to_mime_type.gperf" + {"fpx", "image/vnd.fpx"}, + {"",nullptr}, +#line 744 "auto/extension_to_mime_type.gperf" + {"spc", "application/x-pkcs7-certificates"}, +#line 478 "auto/extension_to_mime_type.gperf" + {"mpc", "application/vnd.mophun.certificate"}, +#line 142 "auto/extension_to_mime_type.gperf" + {"cpp", "text/x-c"}, +#line 975 "auto/extension_to_mime_type.gperf" + {"xsm", "application/vnd.syncml+xml"}, +#line 745 "auto/extension_to_mime_type.gperf" + {"spf", "application/vnd.yamaha.smaf-phrase"}, +#line 867 "auto/extension_to_mime_type.gperf" + {"vcd", "application/x-cdlink"}, +#line 622 "auto/extension_to_mime_type.gperf" + {"ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"}, + {"",nullptr}, +#line 701 "auto/extension_to_mime_type.gperf" + {"sdw", "application/vnd.stardivision.writer"}, +#line 625 "auto/extension_to_mime_type.gperf" + {"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 151 "auto/extension_to_mime_type.gperf" + {"css", "text/css"}, + {"",nullptr}, {"",nullptr}, +#line 940 "auto/extension_to_mime_type.gperf" + {"xdw", "application/vnd.fujixerox.docuworks"}, + {"",nullptr}, {"",nullptr}, +#line 152 "auto/extension_to_mime_type.gperf" + {"cst", "application/x-director"}, +#line 476 "auto/extension_to_mime_type.gperf" + {"mp4s", "application/mp4"}, +#line 270 "auto/extension_to_mime_type.gperf" + {"fst", "image/vnd.fst"}, + {"",nullptr}, +#line 887 "auto/extension_to_mime_type.gperf" + {"wav", "audio/x-wav"}, + {"",nullptr}, {"",nullptr}, +#line 927 "auto/extension_to_mime_type.gperf" + {"x3dv", "model/x3d+vrml"}, +#line 618 "auto/extension_to_mime_type.gperf" + {"ppd", "application/vnd.cups-ppd"}, +#line 454 "auto/extension_to_mime_type.gperf" + {"mj2", "video/mj2"}, + {"",nullptr}, {"",nullptr}, +#line 915 "auto/extension_to_mime_type.gperf" + {"wps", "application/vnd.ms-works"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 150 "auto/extension_to_mime_type.gperf" + {"csp", "application/vnd.commonspace"}, + {"",nullptr}, +#line 758 "auto/extension_to_mime_type.gperf" + {"ssf", "application/vnd.epson.ssf"}, +#line 497 "auto/extension_to_mime_type.gperf" + {"msf", "application/vnd.epson.msf"}, + {"",nullptr}, {"",nullptr}, +#line 474 "auto/extension_to_mime_type.gperf" + {"mp4", "video/mp4"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 923 "auto/extension_to_mime_type.gperf" + {"x32", "application/x-authorware-bin"}, +#line 633 "auto/extension_to_mime_type.gperf" + {"psf", "application/x-font-linux-psf"}, +#line 657 "auto/extension_to_mime_type.gperf" + {"rdf", "application/rdf+xml"}, + {"",nullptr}, {"",nullptr}, +#line 814 "auto/extension_to_mime_type.gperf" + {"tsd", "application/timestamped-data"}, +#line 114 "auto/extension_to_mime_type.gperf" + {"cdxml", "application/vnd.chemdraw+xml"}, + {"",nullptr}, +#line 269 "auto/extension_to_mime_type.gperf" + {"fsc", "application/vnd.fsc.weblaunch"}, +#line 574 "auto/extension_to_mime_type.gperf" + {"p12", "application/x-pkcs12"}, + {"",nullptr}, +#line 455 "auto/extension_to_mime_type.gperf" + {"mjp2", "video/mj2"}, +#line 104 "auto/extension_to_mime_type.gperf" + {"ccxml", "application/ccxml+xml"}, +#line 632 "auto/extension_to_mime_type.gperf" + {"psd", "image/vnd.adobe.photoshop"}, +#line 196 "auto/extension_to_mime_type.gperf" + {"dsc", "text/prs.lines.tag"}, + {"",nullptr}, +#line 435 "auto/extension_to_mime_type.gperf" + {"mc1", "application/vnd.medcalcdata"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 880 "auto/extension_to_mime_type.gperf" + {"vss", "application/vnd.visio"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 976 "auto/extension_to_mime_type.gperf" + {"xspf", "application/xspf+xml"}, +#line 881 "auto/extension_to_mime_type.gperf" + {"vst", "application/vnd.visio"}, +#line 430 "auto/extension_to_mime_type.gperf" + {"mar", "application/octet-stream"}, +#line 641 "auto/extension_to_mime_type.gperf" + {"qam", "application/vnd.epson.quickanime"}, +#line 791 "auto/extension_to_mime_type.gperf" + {"tar", "application/x-tar"}, +#line 197 "auto/extension_to_mime_type.gperf" + {"dssc", "application/dssc+der"}, +#line 707 "auto/extension_to_mime_type.gperf" + {"ser", "application/java-serialized-object"}, + {"",nullptr}, {"",nullptr}, +#line 932 "auto/extension_to_mime_type.gperf" + {"xar", "application/vnd.xara"}, + {"",nullptr}, {"",nullptr}, +#line 913 "auto/extension_to_mime_type.gperf" + {"wpd", "application/vnd.wordperfect"}, +#line 425 "auto/extension_to_mime_type.gperf" + {"ma", "application/mathematica"}, +#line 942 "auto/extension_to_mime_type.gperf" + {"xer", "application/patch-ops-error+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 95 "auto/extension_to_mime_type.gperf" + {"car", "application/vnd.curl.car"}, + {"",nullptr}, +#line 281 "auto/extension_to_mime_type.gperf" + {"gam", "application/x-tads"}, + {"",nullptr}, {"",nullptr}, +#line 116 "auto/extension_to_mime_type.gperf" + {"cer", "application/pkix-cert"}, +#line 930 "auto/extension_to_mime_type.gperf" + {"xaml", "application/xaml+xml"}, + {"",nullptr}, {"",nullptr}, +#line 676 "auto/extension_to_mime_type.gperf" + {"rp9", "application/vnd.cloanto.rp9"}, +#line 26 "auto/extension_to_mime_type.gperf" + {"aas", "application/x-authorware-seg"}, + {"",nullptr}, +#line 25 "auto/extension_to_mime_type.gperf" + {"aam", "application/x-authorware-map"}, +#line 172 "auto/extension_to_mime_type.gperf" + {"der", "application/x-x509-ca-cert"}, +#line 971 "auto/extension_to_mime_type.gperf" + {"xpw", "application/vnd.intercon.formnet"}, + {"",nullptr}, {"",nullptr}, +#line 680 "auto/extension_to_mime_type.gperf" + {"rs", "application/rls-services+xml"}, +#line 879 "auto/extension_to_mime_type.gperf" + {"vsf", "application/vnd.vsf"}, + {"",nullptr}, +#line 167 "auto/extension_to_mime_type.gperf" + {"dd2", "application/vnd.oma.dd2+xml"}, +#line 286 "auto/extension_to_mime_type.gperf" + {"gex", "application/vnd.geometry-explorer"}, +#line 677 "auto/extension_to_mime_type.gperf" + {"rpss", "application/vnd.nokia.radio-presets"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 735 "auto/extension_to_mime_type.gperf" + {"sm", "application/vnd.stepmania.stepchart"}, +#line 751 "auto/extension_to_mime_type.gperf" + {"sql", "application/x-sql"}, +#line 678 "auto/extension_to_mime_type.gperf" + {"rpst", "application/vnd.nokia.radio-preset"}, + {"",nullptr}, +#line 878 "auto/extension_to_mime_type.gperf" + {"vsd", "application/vnd.visio"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 962 "auto/extension_to_mime_type.gperf" + {"xm", "audio/xm"}, + {"",nullptr}, +#line 682 "auto/extension_to_mime_type.gperf" + {"rss", "application/rss+xml"}, +#line 34 "auto/extension_to_mime_type.gperf" + {"aep", "application/vnd.audiograph"}, + {"",nullptr}, +#line 90 "auto/extension_to_mime_type.gperf" + {"c4p", "application/vnd.clonk.c4group"}, +#line 280 "auto/extension_to_mime_type.gperf" + {"gac", "application/vnd.groove-account"}, + {"",nullptr}, {"",nullptr}, +#line 770 "auto/extension_to_mime_type.gperf" + {"sus", "application/vnd.sus-calendar"}, +#line 503 "auto/extension_to_mime_type.gperf" + {"mus", "application/vnd.musician"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 264 "auto/extension_to_mime_type.gperf" + {"fm", "application/vnd.framemaker"}, +#line 298 "auto/extension_to_mime_type.gperf" + {"gqs", "application/vnd.grafeq"}, +#line 24 "auto/extension_to_mime_type.gperf" + {"aac", "audio/x-aac"}, + {"",nullptr}, {"",nullptr}, +#line 935 "auto/extension_to_mime_type.gperf" + {"xbm", "image/x-xbitmap"}, +#line 815 "auto/extension_to_mime_type.gperf" + {"tsv", "text/tab-separated-values"}, +#line 793 "auto/extension_to_mime_type.gperf" + {"tcl", "application/x-tcl"}, +#line 584 "auto/extension_to_mime_type.gperf" + {"pbm", "image/x-portable-bitmap"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 88 "auto/extension_to_mime_type.gperf" + {"c4f", "application/vnd.clonk.c4group"}, + {"",nullptr}, +#line 587 "auto/extension_to_mime_type.gperf" + {"pcl", "application/vnd.hp-pcl"}, + {"",nullptr}, +#line 244 "auto/extension_to_mime_type.gperf" + {"fbs", "image/vnd.fastbidsheet"}, + {"",nullptr}, +#line 97 "auto/extension_to_mime_type.gperf" + {"cb7", "application/x-cbr"}, +#line 974 "auto/extension_to_mime_type.gperf" + {"xslt", "application/xslt+xml"}, +#line 100 "auto/extension_to_mime_type.gperf" + {"cbt", "application/x-cbr"}, +#line 724 "auto/extension_to_mime_type.gperf" + {"sis", "application/vnd.symbian.install"}, +#line 153 "auto/extension_to_mime_type.gperf" + {"csv", "text/csv"}, +#line 185 "auto/extension_to_mime_type.gperf" + {"dms", "application/octet-stream"}, +#line 87 "auto/extension_to_mime_type.gperf" + {"c4d", "application/vnd.clonk.c4group"}, +#line 64 "auto/extension_to_mime_type.gperf" + {"azs", "application/vnd.airzip.filesecure.azs"}, + {"",nullptr}, +#line 726 "auto/extension_to_mime_type.gperf" + {"sit", "application/x-stuffit"}, +#line 494 "auto/extension_to_mime_type.gperf" + {"mscml", "application/mediaservercontrol+xml"}, +#line 477 "auto/extension_to_mime_type.gperf" + {"mp4v", "video/mp4"}, +#line 442 "auto/extension_to_mime_type.gperf" + {"meta4", "application/metalink4+xml"}, +#line 137 "auto/extension_to_mime_type.gperf" + {"cmx", "image/x-cmx"}, + {"",nullptr}, +#line 165 "auto/extension_to_mime_type.gperf" + {"dcr", "application/x-director"}, + {"",nullptr}, +#line 771 "auto/extension_to_mime_type.gperf" + {"susp", "application/vnd.sus-calendar"}, +#line 28 "auto/extension_to_mime_type.gperf" + {"ac", "application/pkix-attr-cert"}, +#line 136 "auto/extension_to_mime_type.gperf" + {"cmp", "application/vnd.yellowriver-custom-menu"}, +#line 470 "auto/extension_to_mime_type.gperf" + {"mp2", "audio/mpeg"}, +#line 736 "auto/extension_to_mime_type.gperf" + {"smf", "application/vnd.stardivision.math"}, +#line 462 "auto/extension_to_mime_type.gperf" + {"mmf", "application/vnd.smaf"}, + {"",nullptr}, +#line 588 "auto/extension_to_mime_type.gperf" + {"pclxl", "application/vnd.hp-pclxl"}, +#line 681 "auto/extension_to_mime_type.gperf" + {"rsd", "application/rsd+xml"}, +#line 297 "auto/extension_to_mime_type.gperf" + {"gqf", "application/vnd.grafeq"}, +#line 184 "auto/extension_to_mime_type.gperf" + {"dmp", "application/vnd.tcpdump.pcap"}, +#line 422 "auto/extension_to_mime_type.gperf" + {"m3u8", "application/vnd.apple.mpegurl"}, + {"",nullptr}, +#line 901 "auto/extension_to_mime_type.gperf" + {"wm", "video/x-ms-wm"}, +#line 177 "auto/extension_to_mime_type.gperf" + {"dis", "application/vnd.mobius.dis"}, + {"",nullptr}, +#line 33 "auto/extension_to_mime_type.gperf" + {"adp", "audio/adpcm"}, +#line 461 "auto/extension_to_mime_type.gperf" + {"mmd", "application/vnd.chipnuts.karaoke-mmd"}, + {"",nullptr}, {"",nullptr}, +#line 133 "auto/extension_to_mime_type.gperf" + {"cmc", "application/vnd.cosmocaller"}, +#line 725 "auto/extension_to_mime_type.gperf" + {"sisx", "application/vnd.symbian.install"}, + {"",nullptr}, +#line 934 "auto/extension_to_mime_type.gperf" + {"xbd", "application/vnd.fujixerox.docuworks.binder"}, +#line 727 "auto/extension_to_mime_type.gperf" + {"sitx", "application/x-stuffitx"}, + {"",nullptr}, +#line 583 "auto/extension_to_mime_type.gperf" + {"pbd", "application/vnd.powerbuilder6"}, + {"",nullptr}, {"",nullptr}, +#line 202 "auto/extension_to_mime_type.gperf" + {"dump", "application/octet-stream"}, +#line 890 "auto/extension_to_mime_type.gperf" + {"wbs", "application/vnd.criticaltools.wbs+xml"}, +#line 452 "auto/extension_to_mime_type.gperf" + {"mif", "application/vnd.mif"}, +#line 882 "auto/extension_to_mime_type.gperf" + {"vsw", "application/vnd.visio"}, +#line 805 "auto/extension_to_mime_type.gperf" + {"tif", "image/tiff"}, +#line 63 "auto/extension_to_mime_type.gperf" + {"azf", "application/vnd.airzip.filesecure.azf"}, +#line 654 "auto/extension_to_mime_type.gperf" + {"rar", "application/x-rar-compressed"}, + {"",nullptr}, +#line 602 "auto/extension_to_mime_type.gperf" + {"pic", "image/x-pict"}, +#line 948 "auto/extension_to_mime_type.gperf" + {"xif", "image/vnd.xiff"}, +#line 178 "auto/extension_to_mime_type.gperf" + {"dist", "application/octet-stream"}, +#line 29 "auto/extension_to_mime_type.gperf" + {"acc", "application/vnd.americandynamics.acc"}, + {"",nullptr}, +#line 720 "auto/extension_to_mime_type.gperf" + {"sid", "image/x-mrsid-image"}, +#line 449 "auto/extension_to_mime_type.gperf" + {"mid", "audio/midi"}, +#line 792 "auto/extension_to_mime_type.gperf" + {"tcap", "application/vnd.3gpp2.tcap"}, + {"",nullptr}, +#line 652 "auto/extension_to_mime_type.gperf" + {"ra", "audio/x-pn-realaudio"}, +#line 910 "auto/extension_to_mime_type.gperf" + {"wmx", "video/x-ms-wmx"}, + {"",nullptr}, {"",nullptr}, +#line 122 "auto/extension_to_mime_type.gperf" + {"cif", "chemical/x-cif"}, + {"",nullptr}, +#line 585 "auto/extension_to_mime_type.gperf" + {"pcap", "application/vnd.tcpdump.pcap"}, + {"",nullptr}, +#line 175 "auto/extension_to_mime_type.gperf" + {"dic", "text/x-c"}, + {"",nullptr}, +#line 746 "auto/extension_to_mime_type.gperf" + {"spl", "application/x-futuresplash"}, + {"",nullptr}, +#line 644 "auto/extension_to_mime_type.gperf" + {"qps", "application/vnd.publishare-delta-tree"}, +#line 809 "auto/extension_to_mime_type.gperf" + {"tpl", "application/vnd.groove-tool-template"}, + {"",nullptr}, {"",nullptr}, +#line 978 "auto/extension_to_mime_type.gperf" + {"xvm", "application/xv+xml"}, +#line 872 "auto/extension_to_mime_type.gperf" + {"vis", "application/vnd.visionary"}, +#line 967 "auto/extension_to_mime_type.gperf" + {"xpl", "application/xproc+xml"}, +#line 679 "auto/extension_to_mime_type.gperf" + {"rq", "application/sparql-query"}, +#line 969 "auto/extension_to_mime_type.gperf" + {"xpr", "application/vnd.is-xpr"}, + {"",nullptr}, +#line 424 "auto/extension_to_mime_type.gperf" + {"m4v", "video/x-m4v"}, + {"",nullptr}, {"",nullptr}, +#line 134 "auto/extension_to_mime_type.gperf" + {"cmdf", "chemical/x-cmdf"}, +#line 889 "auto/extension_to_mime_type.gperf" + {"wbmp", "image/vnd.wap.wbmp"}, + {"",nullptr}, +#line 806 "auto/extension_to_mime_type.gperf" + {"tiff", "image/tiff"}, +#line 904 "auto/extension_to_mime_type.gperf" + {"wmf", "application/x-msmetafile"}, + {"",nullptr}, +#line 279 "auto/extension_to_mime_type.gperf" + {"g3w", "application/vnd.geospace"}, +#line 336 "auto/extension_to_mime_type.gperf" + {"ief", "image/ief"}, +#line 395 "auto/extension_to_mime_type.gperf" + {"lasxml", "application/vnd.las.las+xml"}, +#line 273 "auto/extension_to_mime_type.gperf" + {"fvt", "video/vnd.fvt"}, +#line 668 "auto/extension_to_mime_type.gperf" + {"rm", "application/vnd.rn-realmedia"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 903 "auto/extension_to_mime_type.gperf" + {"wmd", "application/x-ms-wmd"}, + {"",nullptr}, +#line 241 "auto/extension_to_mime_type.gperf" + {"f4v", "video/x-f4v"}, +#line 500 "auto/extension_to_mime_type.gperf" + {"msl", "application/vnd.mobius.msl"}, + {"",nullptr}, +#line 774 "auto/extension_to_mime_type.gperf" + {"svc", "application/vnd.dvb.service"}, + {"",nullptr}, +#line 296 "auto/extension_to_mime_type.gperf" + {"gpx", "application/gpx+xml"}, + {"",nullptr}, {"",nullptr}, +#line 973 "auto/extension_to_mime_type.gperf" + {"xsl", "application/xml"}, + {"",nullptr}, +#line 671 "auto/extension_to_mime_type.gperf" + {"rms", "application/vnd.jcp.javame.midlet-rms"}, + {"",nullptr}, +#line 471 "auto/extension_to_mime_type.gperf" + {"mp21", "application/mp21"}, +#line 789 "auto/extension_to_mime_type.gperf" + {"taglet", "application/vnd.mynfc"}, +#line 335 "auto/extension_to_mime_type.gperf" + {"ics", "text/calendar"}, + {"",nullptr}, +#line 333 "auto/extension_to_mime_type.gperf" + {"icm", "application/vnd.iccprofile"}, + {"",nullptr}, {"",nullptr}, +#line 775 "auto/extension_to_mime_type.gperf" + {"svd", "application/vnd.svd"}, +#line 759 "auto/extension_to_mime_type.gperf" + {"ssml", "application/ssml+xml"}, + {"",nullptr}, {"",nullptr}, +#line 163 "auto/extension_to_mime_type.gperf" + {"davmount", "application/davmount+xml"}, + {"",nullptr}, +#line 739 "auto/extension_to_mime_type.gperf" + {"smv", "video/x-smv"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 617 "auto/extension_to_mime_type.gperf" + {"ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12"}, +#line 670 "auto/extension_to_mime_type.gperf" + {"rmp", "audio/x-pn-realaudio-plugin"}, + {"",nullptr}, +#line 52 "auto/extension_to_mime_type.gperf" + {"asm", "text/x-asm"}, + {"",nullptr}, +#line 664 "auto/extension_to_mime_type.gperf" + {"ris", "application/x-research-info-systems"}, + {"",nullptr}, +#line 914 "auto/extension_to_mime_type.gperf" + {"wpl", "application/vnd.ms-wpl"}, + {"",nullptr}, +#line 149 "auto/extension_to_mime_type.gperf" + {"csml", "chemical/x-csml"}, + {"",nullptr}, {"",nullptr}, +#line 65 "auto/extension_to_mime_type.gperf" + {"azw", "application/vnd.amazon.ebook"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 756 "auto/extension_to_mime_type.gperf" + {"ssdl", "application/ssdl+xml"}, +#line 54 "auto/extension_to_mime_type.gperf" + {"asx", "video/x-ms-asf"}, + {"",nullptr}, +#line 922 "auto/extension_to_mime_type.gperf" + {"wvx", "video/x-ms-wvx"}, +#line 580 "auto/extension_to_mime_type.gperf" + {"p8", "application/pkcs8"}, + {"",nullptr}, {"",nullptr}, +#line 331 "auto/extension_to_mime_type.gperf" + {"icc", "application/vnd.iccprofile"}, + {"",nullptr}, +#line 85 "auto/extension_to_mime_type.gperf" + {"c11amc", "application/vnd.cluetrust.cartomobile-config"}, + {"",nullptr}, +#line 663 "auto/extension_to_mime_type.gperf" + {"rip", "audio/vnd.rip"}, + {"",nullptr}, +#line 402 "auto/extension_to_mime_type.gperf" + {"list", "text/plain"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 397 "auto/extension_to_mime_type.gperf" + {"lbd", "application/vnd.llamagraphics.life-balance.desktop"}, + {"",nullptr}, +#line 304 "auto/extension_to_mime_type.gperf" + {"gsf", "application/x-font-ghostscript"}, +#line 715 "auto/extension_to_mime_type.gperf" + {"sgm", "text/sgml"}, + {"",nullptr}, +#line 109 "auto/extension_to_mime_type.gperf" + {"cdmic", "application/cdmi-container"}, + {"",nullptr}, {"",nullptr}, +#line 50 "auto/extension_to_mime_type.gperf" + {"asc", "application/pgp-signature"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 51 "auto/extension_to_mime_type.gperf" + {"asf", "video/x-ms-asf"}, +#line 110 "auto/extension_to_mime_type.gperf" + {"cdmid", "application/cdmi-domain"}, +#line 599 "auto/extension_to_mime_type.gperf" + {"pgm", "image/x-portable-graymap"}, + {"",nullptr}, +#line 662 "auto/extension_to_mime_type.gperf" + {"rif", "application/reginfo+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 403 "auto/extension_to_mime_type.gperf" + {"list3820", "application/vnd.ibm.modcap"}, + {"",nullptr}, +#line 118 "auto/extension_to_mime_type.gperf" + {"cgm", "image/cgm"}, +#line 447 "auto/extension_to_mime_type.gperf" + {"mgp", "application/vnd.osgeo.mapguide.package"}, +#line 482 "auto/extension_to_mime_type.gperf" + {"mpg4", "video/mp4"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 249 "auto/extension_to_mime_type.gperf" + {"fg5", "application/vnd.fujitsu.oasysgp"}, + {"",nullptr}, {"",nullptr}, +#line 909 "auto/extension_to_mime_type.gperf" + {"wmv", "video/x-ms-wmv"}, + {"",nullptr}, +#line 601 "auto/extension_to_mime_type.gperf" + {"pgp", "application/pgp-encrypted"}, +#line 907 "auto/extension_to_mime_type.gperf" + {"wmls", "text/vnd.wap.wmlscript"}, + {"",nullptr}, {"",nullptr}, +#line 773 "auto/extension_to_mime_type.gperf" + {"sv4crc", "application/x-sv4crc"}, + {"",nullptr}, +#line 533 "auto/extension_to_mime_type.gperf" + {"oas", "application/vnd.fujitsu.oasys"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 891 "auto/extension_to_mime_type.gperf" + {"wbxml", "application/vnd.wap.wbxml"}, + {"",nullptr}, {"",nullptr}, +#line 404 "auto/extension_to_mime_type.gperf" + {"listafp", "application/vnd.ibm.modcap"}, + {"",nullptr}, {"",nullptr}, +#line 824 "auto/extension_to_mime_type.gperf" + {"u32", "application/x-authorware-bin"}, +#line 22 "auto/extension_to_mime_type.gperf" + {"7z", "application/x-7z-compressed"}, + {"",nullptr}, {"",nullptr}, +#line 919 "auto/extension_to_mime_type.gperf" + {"wsdl", "application/wsdl+xml"}, + {"",nullptr}, +#line 908 "auto/extension_to_mime_type.gperf" + {"wmlsc", "application/vnd.wap.wmlscriptc"}, +#line 982 "auto/extension_to_mime_type.gperf" + {"xz", "application/x-xz"}, + {"",nullptr}, +#line 411 "auto/extension_to_mime_type.gperf" + {"lvp", "audio/vnd.lucent.voice"}, + {"",nullptr}, {"",nullptr}, +#line 427 "auto/extension_to_mime_type.gperf" + {"mag", "application/vnd.ecowin.chart"}, + {"",nullptr}, +#line 873 "auto/extension_to_mime_type.gperf" + {"viv", "video/vnd.vivo"}, + {"",nullptr}, {"",nullptr}, +#line 458 "auto/extension_to_mime_type.gperf" + {"mks", "video/x-matroska"}, +#line 729 "auto/extension_to_mime_type.gperf" + {"skm", "application/vnd.koan"}, +#line 174 "auto/extension_to_mime_type.gperf" + {"dgc", "application/x-dgc-compressed"}, + {"",nullptr}, {"",nullptr}, +#line 731 "auto/extension_to_mime_type.gperf" + {"skt", "application/vnd.koan"}, + {"",nullptr}, {"",nullptr}, +#line 906 "auto/extension_to_mime_type.gperf" + {"wmlc", "application/vnd.wap.wmlc"}, + {"",nullptr}, {"",nullptr}, +#line 899 "auto/extension_to_mime_type.gperf" + {"wgt", "application/widget"}, +#line 250 "auto/extension_to_mime_type.gperf" + {"fgd", "application/x-director"}, + {"",nullptr}, {"",nullptr}, +#line 699 "auto/extension_to_mime_type.gperf" + {"sdkm", "application/vnd.solent.sdkm+xml"}, + {"",nullptr}, {"",nullptr}, +#line 796 "auto/extension_to_mime_type.gperf" + {"teicorpus", "application/tei+xml"}, +#line 463 "auto/extension_to_mime_type.gperf" + {"mmr", "image/vnd.fujixerox.edmics-mmr"}, + {"",nullptr}, +#line 730 "auto/extension_to_mime_type.gperf" + {"skp", "application/vnd.koan"}, +#line 639 "auto/extension_to_mime_type.gperf" + {"pya", "audio/vnd.ms-playready.media.pya"}, +#line 977 "auto/extension_to_mime_type.gperf" + {"xul", "application/vnd.mozilla.xul+xml"}, +#line 963 "auto/extension_to_mime_type.gperf" + {"xml", "application/xml"}, + {"",nullptr}, {"",nullptr}, +#line 610 "auto/extension_to_mime_type.gperf" + {"pml", "application/vnd.ctc-posml"}, +#line 692 "auto/extension_to_mime_type.gperf" + {"scq", "application/scvp-cv-request"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 420 "auto/extension_to_mime_type.gperf" + {"m3a", "audio/mpeg"}, +#line 688 "auto/extension_to_mime_type.gperf" + {"sbml", "application/sbml+xml"}, +#line 135 "auto/extension_to_mime_type.gperf" + {"cml", "chemical/x-cml"}, +#line 99 "auto/extension_to_mime_type.gperf" + {"cbr", "application/x-cbr"}, +#line 985 "auto/extension_to_mime_type.gperf" + {"z1", "application/x-zmachine"}, +#line 704 "auto/extension_to_mime_type.gperf" + {"sema", "application/vnd.sema"}, +#line 284 "auto/extension_to_mime_type.gperf" + {"gdl", "model/vnd.gdl"}, +#line 545 "auto/extension_to_mime_type.gperf" + {"ods", "application/vnd.oasis.opendocument.spreadsheet"}, +#line 722 "auto/extension_to_mime_type.gperf" + {"sil", "audio/silk"}, +#line 543 "auto/extension_to_mime_type.gperf" + {"odm", "application/vnd.oasis.opendocument.text-master"}, +#line 866 "auto/extension_to_mime_type.gperf" + {"vcard", "text/vcard"}, + {"",nullptr}, {"",nullptr}, +#line 546 "auto/extension_to_mime_type.gperf" + {"odt", "application/vnd.oasis.opendocument.text"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 293 "auto/extension_to_mime_type.gperf" + {"gmx", "application/vnd.gmx"}, +#line 728 "auto/extension_to_mime_type.gperf" + {"skd", "application/vnd.koan"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 440 "auto/extension_to_mime_type.gperf" + {"me", "text/troff"}, + {"",nullptr}, {"",nullptr}, +#line 124 "auto/extension_to_mime_type.gperf" + {"cil", "application/vnd.ms-artgalry"}, +#line 544 "auto/extension_to_mime_type.gperf" + {"odp", "application/vnd.oasis.opendocument.presentation"}, + {"",nullptr}, {"",nullptr}, +#line 291 "auto/extension_to_mime_type.gperf" + {"gim", "application/vnd.groove-identity-message"}, + {"",nullptr}, {"",nullptr}, +#line 698 "auto/extension_to_mime_type.gperf" + {"sdkd", "application/vnd.solent.sdkm+xml"}, +#line 900 "auto/extension_to_mime_type.gperf" + {"wks", "application/vnd.ms-works"}, + {"",nullptr}, +#line 176 "auto/extension_to_mime_type.gperf" + {"dir", "application/x-director"}, + {"",nullptr}, +#line 626 "auto/extension_to_mime_type.gperf" + {"pqa", "application/vnd.palm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 43 "auto/extension_to_mime_type.gperf" + {"ait", "application/vnd.dvb.ait"}, +#line 538 "auto/extension_to_mime_type.gperf" + {"odc", "application/vnd.oasis.opendocument.chart"}, +#line 695 "auto/extension_to_mime_type.gperf" + {"sda", "application/vnd.stardivision.draw"}, +#line 788 "auto/extension_to_mime_type.gperf" + {"t3", "application/x-t3vm-image"}, +#line 154 "auto/extension_to_mime_type.gperf" + {"cu", "application/cu-seeme"}, +#line 539 "auto/extension_to_mime_type.gperf" + {"odf", "application/vnd.oasis.opendocument.formula"}, + {"",nullptr}, +#line 905 "auto/extension_to_mime_type.gperf" + {"wml", "text/vnd.wap.wml"}, +#line 540 "auto/extension_to_mime_type.gperf" + {"odft", "application/vnd.oasis.opendocument.formula-template"}, +#line 928 "auto/extension_to_mime_type.gperf" + {"x3dvz", "model/x3d+vrml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 387 "auto/extension_to_mime_type.gperf" + {"kpt", "application/vnd.kde.kpresenter"}, + {"",nullptr}, +#line 933 "auto/extension_to_mime_type.gperf" + {"xbap", "application/x-ms-xbap"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 760 "auto/extension_to_mime_type.gperf" + {"st", "application/vnd.sailingtracker.track"}, +#line 421 "auto/extension_to_mime_type.gperf" + {"m3u", "audio/x-mpegurl"}, + {"",nullptr}, +#line 290 "auto/extension_to_mime_type.gperf" + {"gif", "image/gif"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 694 "auto/extension_to_mime_type.gperf" + {"scurl", "text/vnd.curl.scurl"}, +#line 437 "auto/extension_to_mime_type.gperf" + {"mcurl", "text/vnd.curl.mcurl"}, + {"",nullptr}, +#line 749 "auto/extension_to_mime_type.gperf" + {"spq", "application/scvp-vp-request"}, + {"",nullptr}, +#line 39 "auto/extension_to_mime_type.gperf" + {"aif", "audio/x-aiff"}, +#line 779 "auto/extension_to_mime_type.gperf" + {"swf", "application/x-shockwave-flash"}, +#line 506 "auto/extension_to_mime_type.gperf" + {"mwf", "application/vnd.mfer"}, + {"",nullptr}, +#line 502 "auto/extension_to_mime_type.gperf" + {"mts", "model/vnd.mts"}, + {"",nullptr}, +#line 590 "auto/extension_to_mime_type.gperf" + {"pcurl", "application/vnd.curl.pcurl"}, +#line 820 "auto/extension_to_mime_type.gperf" + {"twds", "application/vnd.simtech-mindmapper"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 388 "auto/extension_to_mime_type.gperf" + {"kpxx", "application/vnd.ds-keypoint"}, + {"",nullptr}, {"",nullptr}, +#line 819 "auto/extension_to_mime_type.gperf" + {"twd", "application/vnd.simtech-mindmapper"}, + {"",nullptr}, +#line 979 "auto/extension_to_mime_type.gperf" + {"xvml", "application/xv+xml"}, + {"",nullptr}, {"",nullptr}, +#line 980 "auto/extension_to_mime_type.gperf" + {"xwd", "image/x-xwindowdump"}, + {"",nullptr}, +#line 166 "auto/extension_to_mime_type.gperf" + {"dcurl", "text/vnd.curl.dcurl"}, +#line 214 "auto/extension_to_mime_type.gperf" + {"edm", "application/vnd.novadigm.edm"}, +#line 389 "auto/extension_to_mime_type.gperf" + {"ksp", "application/vnd.kde.kspread"}, + {"",nullptr}, +#line 869 "auto/extension_to_mime_type.gperf" + {"vcg", "application/vnd.groove-vcard"}, +#line 48 "auto/extension_to_mime_type.gperf" + {"apr", "application/vnd.lotus-approach"}, +#line 205 "auto/extension_to_mime_type.gperf" + {"dwf", "model/vnd.dwf"}, +#line 19 "auto/extension_to_mime_type.gperf" + {"3ds", "image/x-3ds"}, +#line 200 "auto/extension_to_mime_type.gperf" + {"dts", "audio/vnd.dts"}, + {"",nullptr}, +#line 346 "auto/extension_to_mime_type.gperf" + {"ims", "application/vnd.ms-ims"}, +#line 703 "auto/extension_to_mime_type.gperf" + {"seed", "application/vnd.fdsn.seed"}, + {"",nullptr}, +#line 459 "auto/extension_to_mime_type.gperf" + {"mkv", "video/x-matroska"}, +#line 40 "auto/extension_to_mime_type.gperf" + {"aifc", "audio/x-aiff"}, +#line 215 "auto/extension_to_mime_type.gperf" + {"edx", "application/vnd.novadigm.edx"}, +#line 481 "auto/extension_to_mime_type.gperf" + {"mpg", "video/mpeg"}, + {"",nullptr}, +#line 41 "auto/extension_to_mime_type.gperf" + {"aiff", "audio/x-aiff"}, +#line 747 "auto/extension_to_mime_type.gperf" + {"spot", "text/vnd.in3d.spot"}, +#line 761 "auto/extension_to_mime_type.gperf" + {"stc", "application/vnd.sun.xml.calc.template"}, + {"",nullptr}, {"",nullptr}, +#line 816 "auto/extension_to_mime_type.gperf" + {"ttc", "application/x-font-ttf"}, +#line 763 "auto/extension_to_mime_type.gperf" + {"stf", "application/vnd.wt.stf"}, + {"",nullptr}, +#line 32 "auto/extension_to_mime_type.gperf" + {"acutc", "application/vnd.acucorp"}, +#line 817 "auto/extension_to_mime_type.gperf" + {"ttf", "application/x-font-ttf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 345 "auto/extension_to_mime_type.gperf" + {"imp", "application/vnd.accpac.simply.imp"}, + {"",nullptr}, {"",nullptr}, +#line 846 "auto/extension_to_mime_type.gperf" + {"uvs", "video/vnd.dece.sd"}, +#line 762 "auto/extension_to_mime_type.gperf" + {"std", "application/vnd.sun.xml.draw.template"}, +#line 844 "auto/extension_to_mime_type.gperf" + {"uvm", "video/vnd.dece.mobile"}, +#line 556 "auto/extension_to_mime_type.gperf" + {"opf", "application/oebps-package+xml"}, +#line 709 "auto/extension_to_mime_type.gperf" + {"setreg", "application/set-registration-initiation"}, + {"",nullptr}, +#line 847 "auto/extension_to_mime_type.gperf" + {"uvt", "application/vnd.dece.ttml+xml"}, +#line 271 "auto/extension_to_mime_type.gperf" + {"ftc", "application/vnd.fluxtime.clip"}, +#line 194 "auto/extension_to_mime_type.gperf" + {"dpg", "application/vnd.dpgraph"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 308 "auto/extension_to_mime_type.gperf" + {"gv", "text/vnd.graphviz"}, +#line 27 "auto/extension_to_mime_type.gperf" + {"abw", "application/x-abiword"}, + {"",nullptr}, {"",nullptr}, +#line 864 "auto/extension_to_mime_type.gperf" + {"uvx", "application/vnd.dece.unspecified"}, +#line 155 "auto/extension_to_mime_type.gperf" + {"curl", "text/vnd.curl"}, + {"",nullptr}, +#line 531 "auto/extension_to_mime_type.gperf" + {"oa2", "application/vnd.fujitsu.oasys2"}, +#line 112 "auto/extension_to_mime_type.gperf" + {"cdmiq", "application/cdmi-queue"}, + {"",nullptr}, +#line 845 "auto/extension_to_mime_type.gperf" + {"uvp", "video/vnd.dece.pd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 377 "auto/extension_to_mime_type.gperf" + {"kar", "audio/midi"}, +#line 199 "auto/extension_to_mime_type.gperf" + {"dtd", "application/xml-dtd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 714 "auto/extension_to_mime_type.gperf" + {"sgl", "application/vnd.stardivision.writer-global"}, +#line 66 "auto/extension_to_mime_type.gperf" + {"bat", "application/x-msdownload"}, +#line 560 "auto/extension_to_mime_type.gperf" + {"osf", "application/vnd.yamaha.openscoreformat"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 181 "auto/extension_to_mime_type.gperf" + {"djvu", "image/vnd.djvu"}, + {"",nullptr}, {"",nullptr}, +#line 840 "auto/extension_to_mime_type.gperf" + {"uvf", "application/vnd.dece.data"}, +#line 344 "auto/extension_to_mime_type.gperf" + {"iif", "application/vnd.shana.informed.interchange"}, + {"",nullptr}, {"",nullptr}, +#line 419 "auto/extension_to_mime_type.gperf" + {"m2v", "video/mpeg"}, + {"",nullptr}, +#line 108 "auto/extension_to_mime_type.gperf" + {"cdmia", "application/cdmi-capability"}, + {"",nullptr}, +#line 795 "auto/extension_to_mime_type.gperf" + {"tei", "application/tei+xml"}, + {"",nullptr}, +#line 716 "auto/extension_to_mime_type.gperf" + {"sgml", "text/sgml"}, + {"",nullptr}, +#line 839 "auto/extension_to_mime_type.gperf" + {"uvd", "application/vnd.dece.data"}, + {"",nullptr}, +#line 225 "auto/extension_to_mime_type.gperf" + {"eps", "application/postscript"}, +#line 412 "auto/extension_to_mime_type.gperf" + {"lwp", "application/vnd.lotus-wordpro"}, +#line 475 "auto/extension_to_mime_type.gperf" + {"mp4a", "audio/mp4"}, +#line 156 "auto/extension_to_mime_type.gperf" + {"cww", "application/prs.cww"}, +#line 288 "auto/extension_to_mime_type.gperf" + {"ggt", "application/vnd.geogebra.tool"}, + {"",nullptr}, {"",nullptr}, +#line 396 "auto/extension_to_mime_type.gperf" + {"latex", "application/x-latex"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 988 "auto/extension_to_mime_type.gperf" + {"z4", "application/x-zmachine"}, + {"",nullptr}, +#line 798 "auto/extension_to_mime_type.gperf" + {"texi", "application/x-texinfo"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 417 "auto/extension_to_mime_type.gperf" + {"m21", "application/mp21"}, + {"",nullptr}, {"",nullptr}, +#line 768 "auto/extension_to_mime_type.gperf" + {"stw", "application/vnd.sun.xml.writer.template"}, + {"",nullptr}, +#line 358 "auto/extension_to_mime_type.gperf" + {"ivp", "application/vnd.immervision-ivp"}, +#line 70 "auto/extension_to_mime_type.gperf" + {"bed", "application/vnd.realvnc.bed"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 858 "auto/extension_to_mime_type.gperf" + {"uvvs", "video/vnd.dece.sd"}, + {"",nullptr}, +#line 856 "auto/extension_to_mime_type.gperf" + {"uvvm", "video/vnd.dece.mobile"}, +#line 69 "auto/extension_to_mime_type.gperf" + {"bdm", "application/vnd.syncml.dm+wbxml"}, +#line 684 "auto/extension_to_mime_type.gperf" + {"rtx", "text/richtext"}, + {"",nullptr}, +#line 859 "auto/extension_to_mime_type.gperf" + {"uvvt", "application/vnd.dece.ttml+xml"}, + {"",nullptr}, {"",nullptr}, +#line 997 "auto/extension_to_mime_type.gperf" + {"zmm", "application/vnd.handheld-entertainment+xml"}, + {"",nullptr}, {"",nullptr}, +#line 898 "auto/extension_to_mime_type.gperf" + {"wg", "application/vnd.pmi.widget"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 862 "auto/extension_to_mime_type.gperf" + {"uvvx", "application/vnd.dece.unspecified"}, +#line 439 "auto/extension_to_mime_type.gperf" + {"mdi", "image/vnd.ms-modi"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 857 "auto/extension_to_mime_type.gperf" + {"uvvp", "video/vnd.dece.pd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 896 "auto/extension_to_mime_type.gperf" + {"webm", "video/webm"}, +#line 410 "auto/extension_to_mime_type.gperf" + {"ltf", "application/vnd.frogans.ltf"}, +#line 683 "auto/extension_to_mime_type.gperf" + {"rtf", "application/rtf"}, + {"",nullptr}, {"",nullptr}, +#line 472 "auto/extension_to_mime_type.gperf" + {"mp2a", "audio/mpeg"}, + {"",nullptr}, +#line 89 "auto/extension_to_mime_type.gperf" + {"c4g", "application/vnd.clonk.c4group"}, + {"",nullptr}, +#line 229 "auto/extension_to_mime_type.gperf" + {"esf", "application/vnd.epson.esf"}, + {"",nullptr}, {"",nullptr}, +#line 292 "auto/extension_to_mime_type.gperf" + {"gml", "application/gml+xml"}, +#line 282 "auto/extension_to_mime_type.gperf" + {"gbr", "application/rpki-ghostbusters"}, +#line 852 "auto/extension_to_mime_type.gperf" + {"uvvf", "application/vnd.dece.data"}, +#line 68 "auto/extension_to_mime_type.gperf" + {"bdf", "application/x-font-bdf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 897 "auto/extension_to_mime_type.gperf" + {"webp", "image/webp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 990 "auto/extension_to_mime_type.gperf" + {"z6", "application/x-zmachine"}, +#line 994 "auto/extension_to_mime_type.gperf" + {"zip", "application/zip"}, +#line 851 "auto/extension_to_mime_type.gperf" + {"uvvd", "application/vnd.dece.data"}, + {"",nullptr}, +#line 849 "auto/extension_to_mime_type.gperf" + {"uvv", "video/vnd.dece.video"}, +#line 634 "auto/extension_to_mime_type.gperf" + {"pskcxml", "application/pskc+xml"}, + {"",nullptr}, +#line 558 "auto/extension_to_mime_type.gperf" + {"oprc", "application/vnd.palm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 504 "auto/extension_to_mime_type.gperf" + {"musicxml", "application/vnd.recordare.musicxml+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 342 "auto/extension_to_mime_type.gperf" + {"igs", "model/iges"}, + {"",nullptr}, +#line 341 "auto/extension_to_mime_type.gperf" + {"igm", "application/vnd.insors.igm"}, + {"",nullptr}, {"",nullptr}, +#line 434 "auto/extension_to_mime_type.gperf" + {"mbox", "application/mbox"}, + {"",nullptr}, +#line 42 "auto/extension_to_mime_type.gperf" + {"air", "application/vnd.adobe.air-application-installer-package+zip"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 179 "auto/extension_to_mime_type.gperf" + {"distz", "application/octet-stream"}, + {"",nullptr}, +#line 238 "auto/extension_to_mime_type.gperf" + {"ez2", "application/vnd.ezpix-album"}, +#line 647 "auto/extension_to_mime_type.gperf" + {"qwt", "application/vnd.quark.quarkxpress"}, + {"",nullptr}, +#line 343 "auto/extension_to_mime_type.gperf" + {"igx", "application/vnd.micrografx.igx"}, +#line 721 "auto/extension_to_mime_type.gperf" + {"sig", "application/pgp-signature"}, +#line 612 "auto/extension_to_mime_type.gperf" + {"pnm", "image/x-portable-anymap"}, +#line 183 "auto/extension_to_mime_type.gperf" + {"dmg", "application/x-apple-diskimage"}, + {"",nullptr}, +#line 386 "auto/extension_to_mime_type.gperf" + {"kpr", "application/vnd.kde.kpresenter"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 534 "auto/extension_to_mime_type.gperf" + {"obd", "application/x-msbinder"}, +#line 941 "auto/extension_to_mime_type.gperf" + {"xenc", "application/xenc+xml"}, +#line 60 "auto/extension_to_mime_type.gperf" + {"au", "audio/basic"}, + {"",nullptr}, +#line 516 "auto/extension_to_mime_type.gperf" + {"nc", "application/x-netcdf"}, +#line 98 "auto/extension_to_mime_type.gperf" + {"cba", "application/x-cbr"}, + {"",nullptr}, {"",nullptr}, +#line 278 "auto/extension_to_mime_type.gperf" + {"g3", "image/g3fax"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 423 "auto/extension_to_mime_type.gperf" + {"m4u", "video/vnd.mpegurl"}, +#line 645 "auto/extension_to_mime_type.gperf" + {"qt", "video/quicktime"}, +#line 256 "auto/extension_to_mime_type.gperf" + {"fig", "application/x-xfig"}, + {"",nullptr}, +#line 283 "auto/extension_to_mime_type.gperf" + {"gca", "application/x-gca-compressed"}, + {"",nullptr}, {"",nullptr}, +#line 517 "auto/extension_to_mime_type.gperf" + {"ncx", "application/x-dtbncx+xml"}, +#line 966 "auto/extension_to_mime_type.gperf" + {"xpi", "application/x-xpinstall"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 742 "auto/extension_to_mime_type.gperf" + {"snf", "application/x-font-snf"}, + {"",nullptr}, {"",nullptr}, +#line 766 "auto/extension_to_mime_type.gperf" + {"stl", "application/vnd.ms-pki.stl"}, + {"",nullptr}, +#line 767 "auto/extension_to_mime_type.gperf" + {"str", "application/vnd.pg.format"}, +#line 818 "auto/extension_to_mime_type.gperf" + {"ttl", "text/turtle"}, +#line 91 "auto/extension_to_mime_type.gperf" + {"c4u", "application/vnd.clonk.c4group"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 741 "auto/extension_to_mime_type.gperf" + {"snd", "audio/basic"}, +#line 835 "auto/extension_to_mime_type.gperf" + {"ustar", "application/x-ustar"}, +#line 837 "auto/extension_to_mime_type.gperf" + {"uu", "text/x-uuencode"}, +#line 646 "auto/extension_to_mime_type.gperf" + {"qwd", "application/vnd.quark.quarkxpress"}, + {"",nullptr}, {"",nullptr}, +#line 265 "auto/extension_to_mime_type.gperf" + {"fnc", "application/vnd.frogans.fnc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 499 "auto/extension_to_mime_type.gperf" + {"msi", "application/x-msdownload"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 306 "auto/extension_to_mime_type.gperf" + {"gtm", "application/vnd.groove-tool-message"}, + {"",nullptr}, {"",nullptr}, +#line 323 "auto/extension_to_mime_type.gperf" + {"hqx", "application/mac-binhex40"}, + {"",nullptr}, +#line 861 "auto/extension_to_mime_type.gperf" + {"uvvv", "video/vnd.dece.video"}, +#line 902 "auto/extension_to_mime_type.gperf" + {"wma", "audio/x-ms-wma"}, +#line 776 "auto/extension_to_mime_type.gperf" + {"svg", "image/svg+xml"}, + {"",nullptr}, {"",nullptr}, +#line 557 "auto/extension_to_mime_type.gperf" + {"opml", "text/x-opml"}, +#line 352 "auto/extension_to_mime_type.gperf" + {"ipfix", "application/ipfix"}, +#line 361 "auto/extension_to_mime_type.gperf" + {"jam", "application/vnd.jam"}, + {"",nullptr}, +#line 62 "auto/extension_to_mime_type.gperf" + {"aw", "application/applixware"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 579 "auto/extension_to_mime_type.gperf" + {"p7s", "application/pkcs7-signature"}, +#line 217 "auto/extension_to_mime_type.gperf" + {"ei6", "application/vnd.pg.osasli"}, +#line 577 "auto/extension_to_mime_type.gperf" + {"p7m", "application/pkcs7-mime"}, + {"",nullptr}, {"",nullptr}, +#line 18 "auto/extension_to_mime_type.gperf" + {"3dml", "text/vnd.in3d.3dml"}, +#line 59 "auto/extension_to_mime_type.gperf" + {"atx", "application/vnd.antix.game-component"}, +#line 738 "auto/extension_to_mime_type.gperf" + {"smil", "application/smil+xml"}, + {"",nullptr}, +#line 992 "auto/extension_to_mime_type.gperf" + {"z8", "application/x-zmachine"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 162 "auto/extension_to_mime_type.gperf" + {"dataless", "application/vnd.fdsn.seed"}, + {"",nullptr}, +#line 242 "auto/extension_to_mime_type.gperf" + {"f77", "text/x-fortran"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 219 "auto/extension_to_mime_type.gperf" + {"emf", "application/x-msmetafile"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 799 "auto/extension_to_mime_type.gperf" + {"texinfo", "application/x-texinfo"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 38 "auto/extension_to_mime_type.gperf" + {"ai", "application/postscript"}, + {"",nullptr}, +#line 31 "auto/extension_to_mime_type.gperf" + {"acu", "application/vnd.acucobol"}, +#line 55 "auto/extension_to_mime_type.gperf" + {"atc", "application/vnd.acucorp"}, + {"",nullptr}, +#line 317 "auto/extension_to_mime_type.gperf" + {"hdf", "application/x-hdf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 526 "auto/extension_to_mime_type.gperf" + {"npx", "image/vnd.net-fpx"}, + {"",nullptr}, +#line 576 "auto/extension_to_mime_type.gperf" + {"p7c", "application/pkcs7-mime"}, + {"",nullptr}, +#line 981 "auto/extension_to_mime_type.gperf" + {"xyz", "chemical/x-xyz"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 360 "auto/extension_to_mime_type.gperf" + {"jad", "text/vnd.sun.j2me.app-descriptor"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 83 "auto/extension_to_mime_type.gperf" + {"bz2", "application/x-bzip2"}, + {"",nullptr}, +#line 111 "auto/extension_to_mime_type.gperf" + {"cdmio", "application/cdmi-object"}, +#line 483 "auto/extension_to_mime_type.gperf" + {"mpga", "audio/mpeg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 656 "auto/extension_to_mime_type.gperf" + {"rcprofile", "application/vnd.ipunplugged.rcprofile"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 277 "auto/extension_to_mime_type.gperf" + {"g2w", "application/vnd.geoplan"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 322 "auto/extension_to_mime_type.gperf" + {"hps", "application/vnd.hp-hps"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 550 "auto/extension_to_mime_type.gperf" + {"ogx", "application/ogg"}, + {"",nullptr}, {"",nullptr}, +#line 432 "auto/extension_to_mime_type.gperf" + {"mb", "application/mathematica"}, +#line 673 "auto/extension_to_mime_type.gperf" + {"rnc", "application/relax-ng-compact-syntax"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 527 "auto/extension_to_mime_type.gperf" + {"nsc", "application/x-conference"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 528 "auto/extension_to_mime_type.gperf" + {"nsf", "application/vnd.lotus-notes"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 381 "auto/extension_to_mime_type.gperf" + {"kml", "application/vnd.google-earth.kml+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 929 "auto/extension_to_mime_type.gperf" + {"x3dz", "model/x3d+xml"}, +#line 790 "auto/extension_to_mime_type.gperf" + {"tao", "application/vnd.tao.intent-module-archive"}, + {"",nullptr}, +#line 803 "auto/extension_to_mime_type.gperf" + {"tga", "image/x-tga"}, +#line 357 "auto/extension_to_mime_type.gperf" + {"itp", "application/vnd.shana.informed.formtemplate"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 307 "auto/extension_to_mime_type.gperf" + {"gtw", "model/vnd.gtw"}, +#line 737 "auto/extension_to_mime_type.gperf" + {"smi", "application/smil+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 76 "auto/extension_to_mime_type.gperf" + {"bmp", "image/bmp"}, + {"",nullptr}, +#line 711 "auto/extension_to_mime_type.gperf" + {"sfs", "application/vnd.spotfire.sfs"}, + {"",nullptr}, {"",nullptr}, +#line 445 "auto/extension_to_mime_type.gperf" + {"mfm", "application/vnd.mfmp"}, + {"",nullptr}, +#line 802 "auto/extension_to_mime_type.gperf" + {"tfm", "application/x-tex-tfm"}, + {"",nullptr}, +#line 446 "auto/extension_to_mime_type.gperf" + {"mft", "application/rpki-manifest"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 995 "auto/extension_to_mime_type.gperf" + {"zir", "application/vnd.zul"}, +#line 596 "auto/extension_to_mime_type.gperf" + {"pfm", "application/x-font-type1"}, + {"",nullptr}, {"",nullptr}, +#line 794 "auto/extension_to_mime_type.gperf" + {"teacher", "application/vnd.smart.teacher"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 117 "auto/extension_to_mime_type.gperf" + {"cfs", "application/x-cfs-compressed"}, + {"",nullptr}, +#line 813 "auto/extension_to_mime_type.gperf" + {"trm", "application/x-msterminal"}, +#line 753 "auto/extension_to_mime_type.gperf" + {"srt", "application/x-subrip"}, +#line 373 "auto/extension_to_mime_type.gperf" + {"jpm", "video/jpm"}, + {"",nullptr}, {"",nullptr}, +#line 598 "auto/extension_to_mime_type.gperf" + {"pfx", "application/x-pkcs12"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 755 "auto/extension_to_mime_type.gperf" + {"srx", "application/sparql-results+xml"}, + {"",nullptr}, +#line 603 "auto/extension_to_mime_type.gperf" + {"pkg", "application/octet-stream"}, +#line 374 "auto/extension_to_mime_type.gperf" + {"js", "application/javascript"}, +#line 123 "auto/extension_to_mime_type.gperf" + {"cii", "application/vnd.anser-web-certificate-issue-initiation"}, +#line 394 "auto/extension_to_mime_type.gperf" + {"kwt", "application/vnd.kde.kword"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 146 "auto/extension_to_mime_type.gperf" + {"crt", "application/x-x509-ca-cert"}, + {"",nullptr}, +#line 457 "auto/extension_to_mime_type.gperf" + {"mka", "audio/x-matroska"}, + {"",nullptr}, +#line 635 "auto/extension_to_mime_type.gperf" + {"ptid", "application/vnd.pvi.ptid1"}, +#line 987 "auto/extension_to_mime_type.gperf" + {"z3", "application/x-zmachine"}, + {"",nullptr}, +#line 340 "auto/extension_to_mime_type.gperf" + {"igl", "application/vnd.igloader"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 752 "auto/extension_to_mime_type.gperf" + {"src", "application/x-wais-source"}, +#line 491 "auto/extension_to_mime_type.gperf" + {"mrc", "application/marc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 46 "auto/extension_to_mime_type.gperf" + {"appcache", "text/cache-manifest"}, +#line 315 "auto/extension_to_mime_type.gperf" + {"hal", "application/vnd.hal+xml"}, +#line 450 "auto/extension_to_mime_type.gperf" + {"midi", "audio/midi"}, +#line 541 "auto/extension_to_mime_type.gperf" + {"odg", "application/vnd.oasis.opendocument.graphics"}, +#line 21 "auto/extension_to_mime_type.gperf" + {"3gp", "video/3gpp"}, +#line 627 "auto/extension_to_mime_type.gperf" + {"prc", "application/x-mobipocket-ebook"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 629 "auto/extension_to_mime_type.gperf" + {"prf", "application/pics-rules"}, +#line 492 "auto/extension_to_mime_type.gperf" + {"mrcx", "application/marcxml+xml"}, + {"",nullptr}, +#line 945 "auto/extension_to_mime_type.gperf" + {"xht", "application/xhtml+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 105 "auto/extension_to_mime_type.gperf" + {"cdbcmsg", "application/vnd.contact.cmsg"}, + {"",nullptr}, {"",nullptr}, +#line 120 "auto/extension_to_mime_type.gperf" + {"chm", "application/vnd.ms-htmlhelp"}, + {"",nullptr}, +#line 237 "auto/extension_to_mime_type.gperf" + {"ez", "application/andrew-inset"}, +#line 536 "auto/extension_to_mime_type.gperf" + {"oda", "application/oda"}, +#line 254 "auto/extension_to_mime_type.gperf" + {"fh7", "image/x-freehand"}, +#line 393 "auto/extension_to_mime_type.gperf" + {"kwd", "application/vnd.kde.kword"}, +#line 253 "auto/extension_to_mime_type.gperf" + {"fh5", "image/x-freehand"}, + {"",nullptr}, +#line 515 "auto/extension_to_mime_type.gperf" + {"nbp", "application/vnd.wolfram.player"}, +#line 549 "auto/extension_to_mime_type.gperf" + {"ogv", "video/ogg"}, +#line 144 "auto/extension_to_mime_type.gperf" + {"crd", "application/x-mscardfile"}, +#line 391 "auto/extension_to_mime_type.gperf" + {"ktx", "image/ktx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 943 "auto/extension_to_mime_type.gperf" + {"xfdf", "application/vnd.adobe.xfdf"}, +#line 804 "auto/extension_to_mime_type.gperf" + {"thmx", "application/vnd.ms-officetheme"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 719 "auto/extension_to_mime_type.gperf" + {"shf", "application/shf+xml"}, +#line 710 "auto/extension_to_mime_type.gperf" + {"sfd-hdstx", "application/vnd.hydrostatix.sof-data"}, +#line 431 "auto/extension_to_mime_type.gperf" + {"mathml", "application/mathml+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 204 "auto/extension_to_mime_type.gperf" + {"dvi", "application/x-dvi"}, +#line 658 "auto/extension_to_mime_type.gperf" + {"rdz", "application/vnd.data-vision.rdz"}, + {"",nullptr}, {"",nullptr}, +#line 418 "auto/extension_to_mime_type.gperf" + {"m2a", "audio/mpeg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 220 "auto/extension_to_mime_type.gperf" + {"eml", "message/rfc822"}, +#line 778 "auto/extension_to_mime_type.gperf" + {"swa", "application/x-director"}, + {"",nullptr}, {"",nullptr}, +#line 255 "auto/extension_to_mime_type.gperf" + {"fhc", "image/x-freehand"}, +#line 443 "auto/extension_to_mime_type.gperf" + {"metalink", "application/metalink+xml"}, +#line 568 "auto/extension_to_mime_type.gperf" + {"ots", "application/vnd.oasis.opendocument.spreadsheet-template"}, + {"",nullptr}, {"",nullptr}, +#line 206 "auto/extension_to_mime_type.gperf" + {"dwg", "image/vnd.dwg"}, +#line 986 "auto/extension_to_mime_type.gperf" + {"z2", "application/x-zmachine"}, +#line 669 "auto/extension_to_mime_type.gperf" + {"rmi", "audio/midi"}, +#line 569 "auto/extension_to_mime_type.gperf" + {"ott", "application/vnd.oasis.opendocument.text-template"}, + {"",nullptr}, +#line 484 "auto/extension_to_mime_type.gperf" + {"mpkg", "application/vnd.apple.installer+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 362 "auto/extension_to_mime_type.gperf" + {"jar", "application/java-archive"}, + {"",nullptr}, +#line 811 "auto/extension_to_mime_type.gperf" + {"tr", "text/troff"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 578 "auto/extension_to_mime_type.gperf" + {"p7r", "application/x-pkcs7-certreqresp"}, +#line 567 "auto/extension_to_mime_type.gperf" + {"otp", "application/vnd.oasis.opendocument.presentation-template"}, + {"",nullptr}, {"",nullptr}, +#line 740 "auto/extension_to_mime_type.gperf" + {"smzip", "application/vnd.stepmania.package"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 712 "auto/extension_to_mime_type.gperf" + {"sfv", "text/x-sfv"}, + {"",nullptr}, {"",nullptr}, +#line 409 "auto/extension_to_mime_type.gperf" + {"lrm", "application/vnd.ms-lrm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 520 "auto/extension_to_mime_type.gperf" + {"nitf", "application/vnd.nitf"}, +#line 252 "auto/extension_to_mime_type.gperf" + {"fh4", "image/x-freehand"}, + {"",nullptr}, +#line 562 "auto/extension_to_mime_type.gperf" + {"otc", "application/vnd.oasis.opendocument.chart-template"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 563 "auto/extension_to_mime_type.gperf" + {"otf", "application/x-font-otf"}, +#line 734 "auto/extension_to_mime_type.gperf" + {"slt", "application/vnd.epson.salt"}, + {"",nullptr}, +#line 954 "auto/extension_to_mime_type.gperf" + {"xls", "application/vnd.ms-excel"}, + {"",nullptr}, +#line 953 "auto/extension_to_mime_type.gperf" + {"xlm", "application/vnd.ms-excel"}, +#line 609 "auto/extension_to_mime_type.gperf" + {"pls", "application/pls+xml"}, + {"",nullptr}, {"",nullptr}, +#line 958 "auto/extension_to_mime_type.gperf" + {"xlt", "application/vnd.ms-excel"}, + {"",nullptr}, +#line 702 "auto/extension_to_mime_type.gperf" + {"see", "application/vnd.seemail"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 713 "auto/extension_to_mime_type.gperf" + {"sgi", "image/sgi"}, +#line 456 "auto/extension_to_mime_type.gperf" + {"mk3d", "video/x-matroska"}, +#line 460 "auto/extension_to_mime_type.gperf" + {"mlp", "application/vnd.dolby.mlp"}, + {"",nullptr}, +#line 428 "auto/extension_to_mime_type.gperf" + {"maker", "application/vnd.framemaker"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 956 "auto/extension_to_mime_type.gperf" + {"xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"}, + {"",nullptr}, {"",nullptr}, +#line 959 "auto/extension_to_mime_type.gperf" + {"xltm", "application/vnd.ms-excel.template.macroenabled.12"}, + {"",nullptr}, {"",nullptr}, +#line 408 "auto/extension_to_mime_type.gperf" + {"lrf", "application/octet-stream"}, + {"",nullptr}, +#line 841 "auto/extension_to_mime_type.gperf" + {"uvg", "image/vnd.dece.graphic"}, +#line 262 "auto/extension_to_mime_type.gperf" + {"flx", "text/vnd.fmi.flexstor"}, +#line 159 "auto/extension_to_mime_type.gperf" + {"dae", "model/vnd.collada+xml"}, + {"",nullptr}, {"",nullptr}, +#line 132 "auto/extension_to_mime_type.gperf" + {"clp", "application/x-msclip"}, +#line 957 "auto/extension_to_mime_type.gperf" + {"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, + {"",nullptr}, {"",nullptr}, +#line 960 "auto/extension_to_mime_type.gperf" + {"xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"}, +#line 213 "auto/extension_to_mime_type.gperf" + {"ecma", "application/ecmascript"}, +#line 951 "auto/extension_to_mime_type.gperf" + {"xlc", "application/vnd.ms-excel"}, +#line 732 "auto/extension_to_mime_type.gperf" + {"sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"}, + {"",nullptr}, +#line 607 "auto/extension_to_mime_type.gperf" + {"plc", "application/vnd.mobius.plc"}, +#line 952 "auto/extension_to_mime_type.gperf" + {"xlf", "application/x-xliff+xml"}, +#line 414 "auto/extension_to_mime_type.gperf" + {"m13", "application/x-msmediaview"}, +#line 82 "auto/extension_to_mime_type.gperf" + {"bz", "application/x-bzip"}, +#line 608 "auto/extension_to_mime_type.gperf" + {"plf", "application/vnd.pocketlearn"}, + {"",nullptr}, +#line 838 "auto/extension_to_mime_type.gperf" + {"uva", "audio/vnd.dece.audio"}, +#line 329 "auto/extension_to_mime_type.gperf" + {"hvs", "application/vnd.yamaha.hv-script"}, + {"",nullptr}, +#line 614 "auto/extension_to_mime_type.gperf" + {"pot", "application/vnd.ms-powerpoint"}, +#line 433 "auto/extension_to_mime_type.gperf" + {"mbk", "application/vnd.mobius.mbk"}, + {"",nullptr}, +#line 733 "auto/extension_to_mime_type.gperf" + {"sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"}, + {"",nullptr}, +#line 139 "auto/extension_to_mime_type.gperf" + {"com", "application/x-msdownload"}, + {"",nullptr}, +#line 946 "auto/extension_to_mime_type.gperf" + {"xhtml", "application/xhtml+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 965 "auto/extension_to_mime_type.gperf" + {"xop", "application/xop+xml"}, + {"",nullptr}, {"",nullptr}, +#line 231 "auto/extension_to_mime_type.gperf" + {"etx", "text/x-setext"}, +#line 190 "auto/extension_to_mime_type.gperf" + {"dot", "application/msword"}, +#line 615 "auto/extension_to_mime_type.gperf" + {"potm", "application/vnd.ms-powerpoint.template.macroenabled.12"}, + {"",nullptr}, +#line 328 "auto/extension_to_mime_type.gperf" + {"hvp", "application/vnd.yamaha.hv-voice"}, +#line 121 "auto/extension_to_mime_type.gperf" + {"chrt", "application/vnd.kde.kchart"}, + {"",nullptr}, {"",nullptr}, +#line 926 "auto/extension_to_mime_type.gperf" + {"x3dbz", "model/x3d+binary"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 164 "auto/extension_to_mime_type.gperf" + {"dbk", "application/docbook+xml"}, + {"",nullptr}, {"",nullptr}, +#line 467 "auto/extension_to_mime_type.gperf" + {"mods", "application/mods+xml"}, +#line 616 "auto/extension_to_mime_type.gperf" + {"potx", "application/vnd.openxmlformats-officedocument.presentationml.template"}, + {"",nullptr}, {"",nullptr}, +#line 191 "auto/extension_to_mime_type.gperf" + {"dotm", "application/vnd.ms-word.template.macroenabled.12"}, + {"",nullptr}, +#line 604 "auto/extension_to_mime_type.gperf" + {"pki", "application/pkixcmp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 561 "auto/extension_to_mime_type.gperf" + {"osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"}, +#line 101 "auto/extension_to_mime_type.gperf" + {"cbz", "application/x-cbr"}, +#line 20 "auto/extension_to_mime_type.gperf" + {"3g2", "video/3gpp2"}, + {"",nullptr}, +#line 364 "auto/extension_to_mime_type.gperf" + {"jisp", "application/vnd.jisp"}, + {"",nullptr}, {"",nullptr}, +#line 496 "auto/extension_to_mime_type.gperf" + {"mseq", "application/vnd.mseq"}, +#line 192 "auto/extension_to_mime_type.gperf" + {"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"}, + {"",nullptr}, +#line 187 "auto/extension_to_mime_type.gperf" + {"doc", "application/msword"}, +#line 188 "auto/extension_to_mime_type.gperf" + {"docm", "application/vnd.ms-word.document.macroenabled.12"}, + {"",nullptr}, +#line 327 "auto/extension_to_mime_type.gperf" + {"hvd", "application/vnd.yamaha.hv-dic"}, +#line 480 "auto/extension_to_mime_type.gperf" + {"mpeg", "video/mpeg"}, +#line 285 "auto/extension_to_mime_type.gperf" + {"geo", "application/vnd.dynageo"}, + {"",nullptr}, {"",nullptr}, +#line 138 "auto/extension_to_mime_type.gperf" + {"cod", "application/vnd.rim.cod"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 597 "auto/extension_to_mime_type.gperf" + {"pfr", "application/font-tdpfr"}, +#line 189 "auto/extension_to_mime_type.gperf" + {"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, + {"",nullptr}, +#line 542 "auto/extension_to_mime_type.gperf" + {"odi", "application/vnd.oasis.opendocument.image"}, +#line 848 "auto/extension_to_mime_type.gperf" + {"uvu", "video/vnd.uvvu.mp4"}, +#line 643 "auto/extension_to_mime_type.gperf" + {"qfx", "application/vnd.intu.qfx"}, + {"",nullptr}, {"",nullptr}, +#line 853 "auto/extension_to_mime_type.gperf" + {"uvvg", "image/vnd.dece.graphic"}, + {"",nullptr}, +#line 44 "auto/extension_to_mime_type.gperf" + {"ami", "application/vnd.amiga.ami"}, +#line 876 "auto/extension_to_mime_type.gperf" + {"vox", "application/x-authorware-bin"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 947 "auto/extension_to_mime_type.gperf" + {"xhvml", "application/xv+xml"}, + {"",nullptr}, {"",nullptr}, +#line 989 "auto/extension_to_mime_type.gperf" + {"z5", "application/x-zmachine"}, + {"",nullptr}, +#line 35 "auto/extension_to_mime_type.gperf" + {"afm", "application/x-font-type1"}, + {"",nullptr}, +#line 228 "auto/extension_to_mime_type.gperf" + {"esa", "application/vnd.osgi.subsystem"}, +#line 145 "auto/extension_to_mime_type.gperf" + {"crl", "application/pkix-crl"}, +#line 961 "auto/extension_to_mime_type.gperf" + {"xlw", "application/vnd.ms-excel"}, +#line 883 "auto/extension_to_mime_type.gperf" + {"vtu", "model/vnd.vtu"}, + {"",nullptr}, +#line 850 "auto/extension_to_mime_type.gperf" + {"uvva", "audio/vnd.dece.audio"}, +#line 911 "auto/extension_to_mime_type.gperf" + {"wmz", "application/x-ms-wmz"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 807 "auto/extension_to_mime_type.gperf" + {"tmo", "application/vnd.tmobile-livetv"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 780 "auto/extension_to_mime_type.gperf" + {"swi", "application/vnd.aristanetworks.swi"}, + {"",nullptr}, +#line 261 "auto/extension_to_mime_type.gperf" + {"flw", "application/vnd.kde.kivio"}, +#line 384 "auto/extension_to_mime_type.gperf" + {"knp", "application/vnd.kinar"}, +#line 36 "auto/extension_to_mime_type.gperf" + {"afp", "application/vnd.ibm.modcap"}, +#line 944 "auto/extension_to_mime_type.gperf" + {"xfdl", "application/vnd.xfdl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 479 "auto/extension_to_mime_type.gperf" + {"mpe", "video/mpeg"}, +#line 380 "auto/extension_to_mime_type.gperf" + {"kia", "application/vnd.kidspiration"}, +#line 260 "auto/extension_to_mime_type.gperf" + {"flv", "video/x-flv"}, +#line 371 "auto/extension_to_mime_type.gperf" + {"jpgm", "video/jpm"}, +#line 248 "auto/extension_to_mime_type.gperf" + {"fe_launch", "application/vnd.denovo.fcselayout-link"}, +#line 666 "auto/extension_to_mime_type.gperf" + {"rlc", "image/vnd.fujixerox.edmics-rlc"}, + {"",nullptr}, +#line 895 "auto/extension_to_mime_type.gperf" + {"weba", "audio/webm"}, +#line 522 "auto/extension_to_mime_type.gperf" + {"nml", "application/vnd.enliven"}, +#line 772 "auto/extension_to_mime_type.gperf" + {"sv4cpio", "application/x-sv4cpio"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 45 "auto/extension_to_mime_type.gperf" + {"apk", "application/vnd.android.package-archive"}, +#line 473 "auto/extension_to_mime_type.gperf" + {"mp3", "audio/mpeg"}, + {"",nullptr}, +#line 390 "auto/extension_to_mime_type.gperf" + {"ktr", "application/vnd.kahootz"}, + {"",nullptr}, {"",nullptr}, +#line 667 "auto/extension_to_mime_type.gperf" + {"rld", "application/resource-lists-diff+xml"}, +#line 359 "auto/extension_to_mime_type.gperf" + {"ivu", "application/vnd.immervision-ivu"}, + {"",nullptr}, +#line 468 "auto/extension_to_mime_type.gperf" + {"mov", "video/quicktime"}, +#line 912 "auto/extension_to_mime_type.gperf" + {"woff", "application/font-woff"}, +#line 918 "auto/extension_to_mime_type.gperf" + {"wrl", "model/vrml"}, +#line 49 "auto/extension_to_mime_type.gperf" + {"arc", "application/x-freearc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 757 "auto/extension_to_mime_type.gperf" + {"sse", "application/vnd.kodak-descriptor"}, + {"",nullptr}, +#line 764 "auto/extension_to_mime_type.gperf" + {"sti", "application/vnd.sun.xml.impress.template"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 464 "auto/extension_to_mime_type.gperf" + {"mng", "video/x-mng"}, + {"",nullptr}, {"",nullptr}, +#line 991 "auto/extension_to_mime_type.gperf" + {"z7", "application/x-zmachine"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 611 "auto/extension_to_mime_type.gperf" + {"png", "image/png"}, +#line 551 "auto/extension_to_mime_type.gperf" + {"omdoc", "application/omdoc+xml"}, + {"",nullptr}, +#line 860 "auto/extension_to_mime_type.gperf" + {"uvvu", "video/vnd.uvvu.mp4"}, +#line 877 "auto/extension_to_mime_type.gperf" + {"vrml", "model/vrml"}, +#line 61 "auto/extension_to_mime_type.gperf" + {"avi", "video/x-msvideo"}, +#line 86 "auto/extension_to_mime_type.gperf" + {"c11amz", "application/vnd.cluetrust.cartomobile-config-pkg"}, + {"",nullptr}, +#line 272 "auto/extension_to_mime_type.gperf" + {"fti", "application/vnd.anser-web-funds-transfer-initiation"}, +#line 173 "auto/extension_to_mime_type.gperf" + {"dfac", "application/vnd.dreamfactory"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 826 "auto/extension_to_mime_type.gperf" + {"ufd", "application/vnd.ufdl"}, + {"",nullptr}, {"",nullptr}, +#line 289 "auto/extension_to_mime_type.gperf" + {"ghf", "application/vnd.groove-help"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 513 "auto/extension_to_mime_type.gperf" + {"n3", "text/n3"}, +#line 47 "auto/extension_to_mime_type.gperf" + {"application", "application/x-ms-application"}, + {"",nullptr}, +#line 338 "auto/extension_to_mime_type.gperf" + {"ifm", "application/vnd.shana.informed.formdata"}, +#line 119 "auto/extension_to_mime_type.gperf" + {"chat", "application/x-chat"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 495 "auto/extension_to_mime_type.gperf" + {"mseed", "application/vnd.fdsn.mseed"}, + {"",nullptr}, {"",nullptr}, +#line 665 "auto/extension_to_mime_type.gperf" + {"rl", "application/resource-lists+xml"}, +#line 186 "auto/extension_to_mime_type.gperf" + {"dna", "application/vnd.dna"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 843 "auto/extension_to_mime_type.gperf" + {"uvi", "image/vnd.dece.graphic"}, + {"",nullptr}, {"",nullptr}, +#line 354 "auto/extension_to_mime_type.gperf" + {"irm", "application/vnd.ibm.rights-management"}, +#line 675 "auto/extension_to_mime_type.gperf" + {"roff", "text/troff"}, +#line 211 "auto/extension_to_mime_type.gperf" + {"ecelp7470", "audio/vnd.nuera.ecelp7470"}, +#line 212 "auto/extension_to_mime_type.gperf" + {"ecelp9600", "audio/vnd.nuera.ecelp9600"}, + {"",nullptr}, {"",nullptr}, +#line 321 "auto/extension_to_mime_type.gperf" + {"hpid", "application/vnd.hp-hpid"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 448 "auto/extension_to_mime_type.gperf" + {"mgz", "application/vnd.proteus.magazine"}, + {"",nullptr}, +#line 993 "auto/extension_to_mime_type.gperf" + {"zaz", "application/vnd.zzazz.deck+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 355 "auto/extension_to_mime_type.gperf" + {"irp", "application/vnd.irepository.package+xml"}, + {"",nullptr}, {"",nullptr}, +#line 305 "auto/extension_to_mime_type.gperf" + {"gtar", "application/x-gtar"}, +#line 56 "auto/extension_to_mime_type.gperf" + {"atom", "application/atom+xml"}, + {"",nullptr}, +#line 353 "auto/extension_to_mime_type.gperf" + {"ipk", "application/vnd.shana.informed.package"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 92 "auto/extension_to_mime_type.gperf" + {"cab", "application/vnd.ms-cab-compressed"}, +#line 334 "auto/extension_to_mime_type.gperf" + {"ico", "image/x-icon"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 339 "auto/extension_to_mime_type.gperf" + {"iges", "model/iges"}, +#line 182 "auto/extension_to_mime_type.gperf" + {"dll", "application/x-msdownload"}, +#line 302 "auto/extension_to_mime_type.gperf" + {"grv", "application/vnd.groove-injector"}, +#line 210 "auto/extension_to_mime_type.gperf" + {"ecelp4800", "audio/vnd.nuera.ecelp4800"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 169 "auto/extension_to_mime_type.gperf" + {"deb", "application/x-debian-package"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 221 "auto/extension_to_mime_type.gperf" + {"emma", "application/emma+xml"}, +#line 53 "auto/extension_to_mime_type.gperf" + {"aso", "application/vnd.accpac.simply.aso"}, + {"",nullptr}, +#line 303 "auto/extension_to_mime_type.gperf" + {"grxml", "application/srgs+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 372 "auto/extension_to_mime_type.gperf" + {"jpgv", "video/jpeg"}, + {"",nullptr}, +#line 529 "auto/extension_to_mime_type.gperf" + {"ntf", "application/vnd.nitf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 950 "auto/extension_to_mime_type.gperf" + {"xlam", "application/vnd.ms-excel.addin.macroenabled.12"}, +#line 723 "auto/extension_to_mime_type.gperf" + {"silo", "model/mesh"}, + {"",nullptr}, {"",nullptr}, +#line 330 "auto/extension_to_mime_type.gperf" + {"i2g", "application/vnd.intergeo"}, + {"",nullptr}, +#line 266 "auto/extension_to_mime_type.gperf" + {"for", "text/x-fortran"}, + {"",nullptr}, +#line 350 "auto/extension_to_mime_type.gperf" + {"install", "application/x-install-instructions"}, +#line 438 "auto/extension_to_mime_type.gperf" + {"mdb", "application/x-msaccess"}, + {"",nullptr}, +#line 126 "auto/extension_to_mime_type.gperf" + {"class", "application/java-vm"}, +#line 325 "auto/extension_to_mime_type.gperf" + {"htm", "text/html"}, + {"",nullptr}, +#line 925 "auto/extension_to_mime_type.gperf" + {"x3db", "model/x3d+binary"}, + {"",nullptr}, {"",nullptr}, +#line 834 "auto/extension_to_mime_type.gperf" + {"urls", "text/uri-list"}, + {"",nullptr}, +#line 592 "auto/extension_to_mime_type.gperf" + {"pdb", "application/vnd.palm"}, + {"",nullptr}, {"",nullptr}, +#line 855 "auto/extension_to_mime_type.gperf" + {"uvvi", "image/vnd.dece.graphic"}, +#line 828 "auto/extension_to_mime_type.gperf" + {"ulx", "application/x-glulx"}, + {"",nullptr}, {"",nullptr}, +#line 407 "auto/extension_to_mime_type.gperf" + {"lostxml", "application/lost+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 548 "auto/extension_to_mime_type.gperf" + {"ogg", "audio/ogg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 320 "auto/extension_to_mime_type.gperf" + {"hpgl", "application/vnd.hp-hpgl"}, +#line 451 "auto/extension_to_mime_type.gperf" + {"mie", "application/x-mie"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 232 "auto/extension_to_mime_type.gperf" + {"eva", "application/x-eva"}, + {"",nullptr}, +#line 257 "auto/extension_to_mime_type.gperf" + {"flac", "audio/x-flac"}, +#line 547 "auto/extension_to_mime_type.gperf" + {"oga", "audio/ogg"}, + {"",nullptr}, {"",nullptr}, +#line 30 "auto/extension_to_mime_type.gperf" + {"ace", "application/x-ace-compressed"}, +#line 314 "auto/extension_to_mime_type.gperf" + {"h264", "video/h264"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 875 "auto/extension_to_mime_type.gperf" + {"vor", "application/vnd.stardivision.writer"}, + {"",nullptr}, +#line 453 "auto/extension_to_mime_type.gperf" + {"mime", "message/rfc822"}, + {"",nullptr}, +#line 510 "auto/extension_to_mime_type.gperf" + {"mxs", "application/vnd.triscape.mxs"}, +#line 785 "auto/extension_to_mime_type.gperf" + {"sxm", "application/vnd.sun.xml.math"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 58 "auto/extension_to_mime_type.gperf" + {"atomsvc", "application/atomsvc+xml"}, +#line 363 "auto/extension_to_mime_type.gperf" + {"java", "text/x-java-source"}, + {"",nullptr}, +#line 823 "auto/extension_to_mime_type.gperf" + {"txt", "text/plain"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 893 "auto/extension_to_mime_type.gperf" + {"wdb", "application/vnd.ms-works"}, + {"",nullptr}, {"",nullptr}, +#line 356 "auto/extension_to_mime_type.gperf" + {"iso", "application/x-iso9660-image"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 201 "auto/extension_to_mime_type.gperf" + {"dtshd", "audio/vnd.dts.hd"}, + {"",nullptr}, +#line 141 "auto/extension_to_mime_type.gperf" + {"cpio", "application/x-cpio"}, + {"",nullptr}, +#line 157 "auto/extension_to_mime_type.gperf" + {"cxt", "application/x-director"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 642 "auto/extension_to_mime_type.gperf" + {"qbo", "application/vnd.intu.qbo"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 158 "auto/extension_to_mime_type.gperf" + {"cxx", "text/x-c"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 781 "auto/extension_to_mime_type.gperf" + {"sxc", "application/vnd.sun.xml.calc"}, +#line 765 "auto/extension_to_mime_type.gperf" + {"stk", "application/hyperstudio"}, + {"",nullptr}, {"",nullptr}, +#line 274 "auto/extension_to_mime_type.gperf" + {"fxp", "application/vnd.adobe.fxp"}, +#line 507 "auto/extension_to_mime_type.gperf" + {"mxf", "application/mxf"}, + {"",nullptr}, +#line 822 "auto/extension_to_mime_type.gperf" + {"txf", "application/vnd.mobius.txf"}, + {"",nullptr}, {"",nullptr}, +#line 208 "auto/extension_to_mime_type.gperf" + {"dxp", "application/vnd.spotfire.dxp"}, + {"",nullptr}, {"",nullptr}, +#line 370 "auto/extension_to_mime_type.gperf" + {"jpg", "image/jpeg"}, + {"",nullptr}, {"",nullptr}, +#line 782 "auto/extension_to_mime_type.gperf" + {"sxd", "application/vnd.sun.xml.draw"}, +#line 294 "auto/extension_to_mime_type.gperf" + {"gnumeric", "application/x-gnumeric"}, +#line 519 "auto/extension_to_mime_type.gperf" + {"ngdat", "application/vnd.nokia.n-gage.data"}, +#line 821 "auto/extension_to_mime_type.gperf" + {"txd", "application/vnd.genomatix.tuxedo"}, + {"",nullptr}, {"",nullptr}, +#line 594 "auto/extension_to_mime_type.gperf" + {"pfa", "application/x-font-type1"}, + {"",nullptr}, {"",nullptr}, +#line 429 "auto/extension_to_mime_type.gperf" + {"man", "text/troff"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 812 "auto/extension_to_mime_type.gperf" + {"tra", "application/vnd.trueapp"}, +#line 207 "auto/extension_to_mime_type.gperf" + {"dxf", "image/vnd.dxf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 299 "auto/extension_to_mime_type.gperf" + {"gram", "application/srgs"}, + {"",nullptr}, {"",nullptr}, +#line 631 "auto/extension_to_mime_type.gperf" + {"psb", "application/vnd.3gpp.pic-bw-small"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 398 "auto/extension_to_mime_type.gperf" + {"lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"}, + {"",nullptr}, +#line 777 "auto/extension_to_mime_type.gperf" + {"svgz", "image/svg+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 332 "auto/extension_to_mime_type.gperf" + {"ice", "x-conference/x-cooltalk"}, +#line 195 "auto/extension_to_mime_type.gperf" + {"dra", "audio/vnd.dra"}, + {"",nullptr}, +#line 300 "auto/extension_to_mime_type.gperf" + {"gramps", "application/x-gramps-xml"}, + {"",nullptr}, {"",nullptr}, +#line 718 "auto/extension_to_mime_type.gperf" + {"shar", "application/x-shar"}, +#line 827 "auto/extension_to_mime_type.gperf" + {"ufdl", "application/vnd.ufdl"}, +#line 312 "auto/extension_to_mime_type.gperf" + {"h261", "video/h261"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 524 "auto/extension_to_mime_type.gperf" + {"nns", "application/vnd.noblenet-sealer"}, + {"",nullptr}, {"",nullptr}, +#line 865 "auto/extension_to_mime_type.gperf" + {"uvz", "application/vnd.dece.zip"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 754 "auto/extension_to_mime_type.gperf" + {"sru", "application/sru+xml"}, + {"",nullptr}, +#line 786 "auto/extension_to_mime_type.gperf" + {"sxw", "application/vnd.sun.xml.writer"}, +#line 311 "auto/extension_to_mime_type.gperf" + {"h", "text/x-c"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 564 "auto/extension_to_mime_type.gperf" + {"otg", "application/vnd.oasis.opendocument.graphics-template"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 67 "auto/extension_to_mime_type.gperf" + {"bcpio", "application/x-bcpio"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 523 "auto/extension_to_mime_type.gperf" + {"nnd", "application/vnd.noblenet-directory"}, +#line 129 "auto/extension_to_mime_type.gperf" + {"clkt", "application/vnd.crick.clicker.template"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 131 "auto/extension_to_mime_type.gperf" + {"clkx", "application/vnd.crick.clicker"}, + {"",nullptr}, +#line 23 "auto/extension_to_mime_type.gperf" + {"aab", "application/x-authorware-bin"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 128 "auto/extension_to_mime_type.gperf" + {"clkp", "application/vnd.crick.clicker.palette"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 743 "auto/extension_to_mime_type.gperf" + {"so", "application/octet-stream"}, + {"",nullptr}, {"",nullptr}, +#line 532 "auto/extension_to_mime_type.gperf" + {"oa3", "application/vnd.fujitsu.oasys3"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 964 "auto/extension_to_mime_type.gperf" + {"xo", "application/vnd.olpc-sugar"}, + {"",nullptr}, {"",nullptr}, +#line 441 "auto/extension_to_mime_type.gperf" + {"mesh", "model/mesh"}, +#line 382 "auto/extension_to_mime_type.gperf" + {"kmz", "application/vnd.google-earth.kmz"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 863 "auto/extension_to_mime_type.gperf" + {"uvvz", "application/vnd.dece.zip"}, + {"",nullptr}, {"",nullptr}, +#line 769 "auto/extension_to_mime_type.gperf" + {"sub", "image/vnd.dvb.subtitle"}, + {"",nullptr}, {"",nullptr}, +#line 57 "auto/extension_to_mime_type.gperf" + {"atomcat", "application/atomcat+xml"}, + {"",nullptr}, {"",nullptr}, +#line 949 "auto/extension_to_mime_type.gperf" + {"xla", "application/vnd.ms-excel"}, + {"",nullptr}, {"",nullptr}, +#line 833 "auto/extension_to_mime_type.gperf" + {"uris", "text/uri-list"}, +#line 486 "auto/extension_to_mime_type.gperf" + {"mpn", "application/vnd.mophun.application"}, +#line 636 "auto/extension_to_mime_type.gperf" + {"pub", "application/x-mspublisher"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 75 "auto/extension_to_mime_type.gperf" + {"bmi", "application/vnd.bmi"}, + {"",nullptr}, +#line 125 "auto/extension_to_mime_type.gperf" + {"cla", "application/vnd.claymore"}, +#line 401 "auto/extension_to_mime_type.gperf" + {"link66", "application/vnd.route66.link66+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 326 "auto/extension_to_mime_type.gperf" + {"html", "text/html"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 400 "auto/extension_to_mime_type.gperf" + {"lha", "application/x-lzh-compressed"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 525 "auto/extension_to_mime_type.gperf" + {"nnw", "application/vnd.noblenet-web"}, + {"",nullptr}, {"",nullptr}, +#line 801 "auto/extension_to_mime_type.gperf" + {"tfi", "application/thraud+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 81 "auto/extension_to_mime_type.gperf" + {"btif", "image/prs.btif"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 508 "auto/extension_to_mime_type.gperf" + {"mxl", "application/vnd.recordare.musicxml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 831 "auto/extension_to_mime_type.gperf" + {"uoml", "application/vnd.uoml+xml"}, + {"",nullptr}, +#line 651 "auto/extension_to_mime_type.gperf" + {"qxt", "application/vnd.quark.quarkxpress"}, + {"",nullptr}, {"",nullptr}, +#line 80 "auto/extension_to_mime_type.gperf" + {"bpk", "application/octet-stream"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 514 "auto/extension_to_mime_type.gperf" + {"nb", "application/mathematica"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 509 "auto/extension_to_mime_type.gperf" + {"mxml", "application/xv+xml"}, + {"",nullptr}, {"",nullptr}, +#line 605 "auto/extension_to_mime_type.gperf" + {"pkipath", "application/pkix-pkipath"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 310 "auto/extension_to_mime_type.gperf" + {"gxt", "application/vnd.geonext"}, + {"",nullptr}, +#line 209 "auto/extension_to_mime_type.gperf" + {"dxr", "application/x-director"}, + {"",nullptr}, +#line 130 "auto/extension_to_mime_type.gperf" + {"clkw", "application/vnd.crick.clicker.wordbank"}, + {"",nullptr}, {"",nullptr}, +#line 505 "auto/extension_to_mime_type.gperf" + {"mvb", "application/x-msmediaview"}, +#line 349 "auto/extension_to_mime_type.gperf" + {"inkml", "application/inkml+xml"}, +#line 218 "auto/extension_to_mime_type.gperf" + {"elc", "application/octet-stream"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 637 "auto/extension_to_mime_type.gperf" + {"pvb", "application/vnd.3gpp.pic-bw-var"}, +#line 224 "auto/extension_to_mime_type.gperf" + {"eot", "application/vnd.ms-fontobject"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 275 "auto/extension_to_mime_type.gperf" + {"fxpl", "application/vnd.adobe.fxp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 649 "auto/extension_to_mime_type.gperf" + {"qxd", "application/vnd.quark.quarkxpress"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 203 "auto/extension_to_mime_type.gperf" + {"dvb", "video/vnd.dvb.file"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 309 "auto/extension_to_mime_type.gperf" + {"gxf", "application/gxf"}, + {"",nullptr}, {"",nullptr}, +#line 917 "auto/extension_to_mime_type.gperf" + {"wri", "application/x-mswrite"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 222 "auto/extension_to_mime_type.gperf" + {"emz", "application/x-msmetafile"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 239 "auto/extension_to_mime_type.gperf" + {"ez3", "application/vnd.ezpix-package"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 884 "auto/extension_to_mime_type.gperf" + {"vxml", "application/voicexml+xml"}, + {"",nullptr}, {"",nullptr}, +#line 406 "auto/extension_to_mime_type.gperf" + {"log", "text/plain"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 498 "auto/extension_to_mime_type.gperf" + {"msh", "model/mesh"}, + {"",nullptr}, +#line 566 "auto/extension_to_mime_type.gperf" + {"oti", "application/vnd.oasis.opendocument.image-template"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 413 "auto/extension_to_mime_type.gperf" + {"lzh", "application/x-lzh-compressed"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 17 "auto/extension_to_mime_type.gperf" + {"123", "application/vnd.lotus-1-2-3"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 674 "auto/extension_to_mime_type.gperf" + {"roa", "application/rpki-roa"}, + {"",nullptr}, +#line 148 "auto/extension_to_mime_type.gperf" + {"csh", "application/x-csh"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 996 "auto/extension_to_mime_type.gperf" + {"zirz", "application/vnd.zul"}, + {"",nullptr}, +#line 836 "auto/extension_to_mime_type.gperf" + {"utz", "application/vnd.uiq.theme"}, +#line 405 "auto/extension_to_mime_type.gperf" + {"lnk", "application/x-ms-shortcut"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 316 "auto/extension_to_mime_type.gperf" + {"hbci", "application/vnd.hbci"}, +#line 366 "auto/extension_to_mime_type.gperf" + {"jnlp", "application/x-java-jnlp-file"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 717 "auto/extension_to_mime_type.gperf" + {"sh", "application/x-sh"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 258 "auto/extension_to_mime_type.gperf" + {"fli", "video/x-fli"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 672 "auto/extension_to_mime_type.gperf" + {"rmvb", "application/vnd.rn-realmedia-vbr"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 251 "auto/extension_to_mime_type.gperf" + {"fh", "image/x-freehand"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 78 "auto/extension_to_mime_type.gperf" + {"box", "application/vnd.previewsystems.box"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 268 "auto/extension_to_mime_type.gperf" + {"frame", "application/vnd.framemaker"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 227 "auto/extension_to_mime_type.gperf" + {"es3", "application/vnd.eszigno3+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 347 "auto/extension_to_mime_type.gperf" + {"in", "text/plain"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 537 "auto/extension_to_mime_type.gperf" + {"odb", "application/vnd.oasis.opendocument.database"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 71 "auto/extension_to_mime_type.gperf" + {"bh2", "application/vnd.fujitsu.oasysprs"}, + {"",nullptr}, +#line 553 "auto/extension_to_mime_type.gperf" + {"onetmp", "application/onenote"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 554 "auto/extension_to_mime_type.gperf" + {"onetoc", "application/onenote"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 661 "auto/extension_to_mime_type.gperf" + {"rgb", "image/x-rgb"}, + {"",nullptr}, {"",nullptr}, +#line 650 "auto/extension_to_mime_type.gperf" + {"qxl", "application/vnd.quark.quarkxpress"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 571 "auto/extension_to_mime_type.gperf" + {"oxt", "application/vnd.openofficeorg.extension"}, +#line 319 "auto/extension_to_mime_type.gperf" + {"hlp", "application/winhlp"}, +#line 216 "auto/extension_to_mime_type.gperf" + {"efif", "application/vnd.picsel"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 392 "auto/extension_to_mime_type.gperf" + {"ktz", "application/vnd.kahootz"}, +#line 223 "auto/extension_to_mime_type.gperf" + {"eol", "audio/vnd.digital-winds"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 783 "auto/extension_to_mime_type.gperf" + {"sxg", "application/vnd.sun.xml.writer.global"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 570 "auto/extension_to_mime_type.gperf" + {"oxps", "application/oxps"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 600 "auto/extension_to_mime_type.gperf" + {"pgn", "application/x-chess-pgn"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 832 "auto/extension_to_mime_type.gperf" + {"uri", "text/uri-list"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 559 "auto/extension_to_mime_type.gperf" + {"org", "application/vnd.lotus-organizer"}, + {"",nullptr}, {"",nullptr}, +#line 140 "auto/extension_to_mime_type.gperf" + {"conf", "text/plain"}, +#line 198 "auto/extension_to_mime_type.gperf" + {"dtb", "application/x-dtbook+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 555 "auto/extension_to_mime_type.gperf" + {"onetoc2", "application/onenote"}, +#line 365 "auto/extension_to_mime_type.gperf" + {"jlt", "application/vnd.hp-jlyt"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 295 "auto/extension_to_mime_type.gperf" + {"gph", "application/vnd.flographit"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 613 "auto/extension_to_mime_type.gperf" + {"portpkg", "application/vnd.macports.portpkg"}, + {"",nullptr}, {"",nullptr}, +#line 490 "auto/extension_to_mime_type.gperf" + {"mqy", "application/vnd.mobius.mqy"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 921 "auto/extension_to_mime_type.gperf" + {"wtb", "application/vnd.webturbo"}, + {"",nullptr}, +#line 708 "auto/extension_to_mime_type.gperf" + {"setpay", "application/set-payment-initiation"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 236 "auto/extension_to_mime_type.gperf" + {"ext", "application/vnd.novadigm.ext"}, +#line 348 "auto/extension_to_mime_type.gperf" + {"ink", "application/inkml+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 511 "auto/extension_to_mime_type.gperf" + {"mxu", "video/vnd.mpegurl"}, + {"",nullptr}, +#line 351 "auto/extension_to_mime_type.gperf" + {"iota", "application/vnd.astraea-software.iota"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 115 "auto/extension_to_mime_type.gperf" + {"cdy", "application/vnd.cinderella"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 287 "auto/extension_to_mime_type.gperf" + {"ggb", "application/vnd.geogebra.file"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 920 "auto/extension_to_mime_type.gperf" + {"wspolicy", "application/wspolicy+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 369 "auto/extension_to_mime_type.gperf" + {"jpeg", "image/jpeg"}, + {"",nullptr}, +#line 107 "auto/extension_to_mime_type.gperf" + {"cdkey", "application/vnd.mediastation.cdkey"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 638 "auto/extension_to_mime_type.gperf" + {"pwn", "application/vnd.3m.post-it-notes"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 259 "auto/extension_to_mime_type.gperf" + {"flo", "application/vnd.micrografx.flo"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 489 "auto/extension_to_mime_type.gperf" + {"mpy", "application/vnd.ibm.minipay"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 368 "auto/extension_to_mime_type.gperf" + {"jpe", "image/jpeg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 628 "auto/extension_to_mime_type.gperf" + {"pre", "application/vnd.lotus-freelance"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 784 "auto/extension_to_mime_type.gperf" + {"sxi", "application/vnd.sun.xml.impress"}, + {"",nullptr}, {"",nullptr}, +#line 469 "auto/extension_to_mime_type.gperf" + {"movie", "video/x-sgi-movie"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 501 "auto/extension_to_mime_type.gperf" + {"msty", "application/vnd.muvee.style"}, + {"",nullptr}, +#line 37 "auto/extension_to_mime_type.gperf" + {"ahead", "application/vnd.ahead.space"}, +#line 171 "auto/extension_to_mime_type.gperf" + {"deploy", "application/octet-stream"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 530 "auto/extension_to_mime_type.gperf" + {"nzb", "application/x-nzb"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 808 "auto/extension_to_mime_type.gperf" + {"torrent", "application/x-bittorrent"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 830 "auto/extension_to_mime_type.gperf" + {"unityweb", "application/vnd.unity"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 575 "auto/extension_to_mime_type.gperf" + {"p7b", "application/x-pkcs7-certificates"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 983 "auto/extension_to_mime_type.gperf" + {"yang", "application/yang"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 842 "auto/extension_to_mime_type.gperf" + {"uvh", "video/vnd.dece.hd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 825 "auto/extension_to_mime_type.gperf" + {"udeb", "application/x-debian-package"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 829 "auto/extension_to_mime_type.gperf" + {"umj", "application/vnd.umajin"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 230 "auto/extension_to_mime_type.gperf" + {"et3", "application/vnd.eszigno3+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 854 "auto/extension_to_mime_type.gperf" + {"uvvh", "video/vnd.dece.hd"}, + {"",nullptr}, +#line 595 "auto/extension_to_mime_type.gperf" + {"pfb", "application/x-font-type1"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 226 "auto/extension_to_mime_type.gperf" + {"epub", "application/epub+zip"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 383 "auto/extension_to_mime_type.gperf" + {"kne", "application/vnd.kinar"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 301 "auto/extension_to_mime_type.gperf" + {"gre", "application/vnd.geometry-explorer"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 552 "auto/extension_to_mime_type.gperf" + {"onepkg", "application/onenote"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 379 "auto/extension_to_mime_type.gperf" + {"kfo", "application/vnd.kde.kformula"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 512 "auto/extension_to_mime_type.gperf" + {"n-gage", "application/vnd.nokia.n-gage.symbian.install"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 521 "auto/extension_to_mime_type.gperf" + {"nlu", "application/vnd.neurolanguage.nlu"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 127 "auto/extension_to_mime_type.gperf" + {"clkk", "application/vnd.crick.clicker.keyboard"}, + {"",nullptr}, +#line 606 "auto/extension_to_mime_type.gperf" + {"plb", "application/vnd.3gpp.pic-bw-large"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 72 "auto/extension_to_mime_type.gperf" + {"bin", "application/octet-stream"}, +#line 955 "auto/extension_to_mime_type.gperf" + {"xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 535 "auto/extension_to_mime_type.gperf" + {"obj", "application/x-tgif"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 313 "auto/extension_to_mime_type.gperf" + {"h263", "video/h263"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 376 "auto/extension_to_mime_type.gperf" + {"jsonml", "application/jsonml+json"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 466 "auto/extension_to_mime_type.gperf" + {"mobi", "application/x-mobipocket-ebook"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 874 "auto/extension_to_mime_type.gperf" + {"vob", "video/x-ms-vob"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 367 "auto/extension_to_mime_type.gperf" + {"joda", "application/vnd.joost.joda-archive"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 318 "auto/extension_to_mime_type.gperf" + {"hh", "text/x-c"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 337 "auto/extension_to_mime_type.gperf" + {"ifb", "text/calendar"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 565 "auto/extension_to_mime_type.gperf" + {"oth", "application/vnd.oasis.opendocument.text-web"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 518 "auto/extension_to_mime_type.gperf" + {"nfo", "text/x-nfo"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 235 "auto/extension_to_mime_type.gperf" + {"exi", "application/exi"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 79 "auto/extension_to_mime_type.gperf" + {"boz", "application/x-bzip2"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 465 "auto/extension_to_mime_type.gperf" + {"mny", "application/x-msmoney"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 378 "auto/extension_to_mime_type.gperf" + {"karbon", "application/vnd.kde.karbon"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 984 "auto/extension_to_mime_type.gperf" + {"yin", "application/yin+xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 233 "auto/extension_to_mime_type.gperf" + {"evy", "application/x-envoy"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 324 "auto/extension_to_mime_type.gperf" + {"htke", "application/vnd.kenameaapp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 375 "auto/extension_to_mime_type.gperf" + {"json", "application/json"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 648 "auto/extension_to_mime_type.gperf" + {"qxb", "application/vnd.quark.quarkxpress"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 74 "auto/extension_to_mime_type.gperf" + {"blorb", "application/x-blorb"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 147 "auto/extension_to_mime_type.gperf" + {"cryptonote", "application/vnd.rig.cryptonote"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 385 "auto/extension_to_mime_type.gperf" + {"kon", "application/vnd.kde.kontour"}, +#line 263 "auto/extension_to_mime_type.gperf" + {"fly", "text/vnd.fly"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 73 "auto/extension_to_mime_type.gperf" + {"blb", "application/x-blorb"}, + {"",nullptr}, +#line 234 "auto/extension_to_mime_type.gperf" + {"exe", "application/x-msdownload"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 77 "auto/extension_to_mime_type.gperf" + {"book", "application/vnd.framemaker"} + }; + + if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) + { + unsigned int key = extension_hash (str, len); + + if (key <= MAX_HASH_VALUE) + { + register const char *s = wordlist[key].extension; + + if ((((unsigned char)*str ^ (unsigned char)*s) & ~32) == 0 && !gperf_case_strcmp (str, s)) + return &wordlist[key]; + } + } + return 0; +} +#line 998 "auto/extension_to_mime_type.gperf" + +const char *extension_to_mime_type(const char *extension, size_t extension_len) { + const auto &result = search_extension(extension, extension_len); + if (result == nullptr) { + return nullptr; + } + + return result->mime_type; +} diff --git a/submodules/ton/tonlib-src/tdutils/generate/auto/extension_to_mime_type.gperf b/submodules/ton/tonlib-src/tdutils/generate/auto/extension_to_mime_type.gperf new file mode 100644 index 00000000000..8f91fa4a713 --- /dev/null +++ b/submodules/ton/tonlib-src/tdutils/generate/auto/extension_to_mime_type.gperf @@ -0,0 +1,1006 @@ +%struct-type +%ignore-case +%language=ANSI-C +%readonly-tables +%includes +%enum +%define slot-name extension +%define initializer-suffix ,nullptr +%define slot-name extension +%define hash-function-name extension_hash +%define lookup-function-name search_extension +struct extension_and_mime_type { + const char *extension; + const char *mime_type; +} +%% +"123", "application/vnd.lotus-1-2-3" +"3dml", "text/vnd.in3d.3dml" +"3ds", "image/x-3ds" +"3g2", "video/3gpp2" +"3gp", "video/3gpp" +"7z", "application/x-7z-compressed" +"aab", "application/x-authorware-bin" +"aac", "audio/x-aac" +"aam", "application/x-authorware-map" +"aas", "application/x-authorware-seg" +"abw", "application/x-abiword" +"ac", "application/pkix-attr-cert" +"acc", "application/vnd.americandynamics.acc" +"ace", "application/x-ace-compressed" +"acu", "application/vnd.acucobol" +"acutc", "application/vnd.acucorp" +"adp", "audio/adpcm" +"aep", "application/vnd.audiograph" +"afm", "application/x-font-type1" +"afp", "application/vnd.ibm.modcap" +"ahead", "application/vnd.ahead.space" +"ai", "application/postscript" +"aif", "audio/x-aiff" +"aifc", "audio/x-aiff" +"aiff", "audio/x-aiff" +"air", "application/vnd.adobe.air-application-installer-package+zip" +"ait", "application/vnd.dvb.ait" +"ami", "application/vnd.amiga.ami" +"apk", "application/vnd.android.package-archive" +"appcache", "text/cache-manifest" +"application", "application/x-ms-application" +"apr", "application/vnd.lotus-approach" +"arc", "application/x-freearc" +"asc", "application/pgp-signature" +"asf", "video/x-ms-asf" +"asm", "text/x-asm" +"aso", "application/vnd.accpac.simply.aso" +"asx", "video/x-ms-asf" +"atc", "application/vnd.acucorp" +"atom", "application/atom+xml" +"atomcat", "application/atomcat+xml" +"atomsvc", "application/atomsvc+xml" +"atx", "application/vnd.antix.game-component" +"au", "audio/basic" +"avi", "video/x-msvideo" +"aw", "application/applixware" +"azf", "application/vnd.airzip.filesecure.azf" +"azs", "application/vnd.airzip.filesecure.azs" +"azw", "application/vnd.amazon.ebook" +"bat", "application/x-msdownload" +"bcpio", "application/x-bcpio" +"bdf", "application/x-font-bdf" +"bdm", "application/vnd.syncml.dm+wbxml" +"bed", "application/vnd.realvnc.bed" +"bh2", "application/vnd.fujitsu.oasysprs" +"bin", "application/octet-stream" +"blb", "application/x-blorb" +"blorb", "application/x-blorb" +"bmi", "application/vnd.bmi" +"bmp", "image/bmp" +"book", "application/vnd.framemaker" +"box", "application/vnd.previewsystems.box" +"boz", "application/x-bzip2" +"bpk", "application/octet-stream" +"btif", "image/prs.btif" +"bz", "application/x-bzip" +"bz2", "application/x-bzip2" +"c", "text/x-c" +"c11amc", "application/vnd.cluetrust.cartomobile-config" +"c11amz", "application/vnd.cluetrust.cartomobile-config-pkg" +"c4d", "application/vnd.clonk.c4group" +"c4f", "application/vnd.clonk.c4group" +"c4g", "application/vnd.clonk.c4group" +"c4p", "application/vnd.clonk.c4group" +"c4u", "application/vnd.clonk.c4group" +"cab", "application/vnd.ms-cab-compressed" +"caf", "audio/x-caf" +"cap", "application/vnd.tcpdump.pcap" +"car", "application/vnd.curl.car" +"cat", "application/vnd.ms-pki.seccat" +"cb7", "application/x-cbr" +"cba", "application/x-cbr" +"cbr", "application/x-cbr" +"cbt", "application/x-cbr" +"cbz", "application/x-cbr" +"cc", "text/x-c" +"cct", "application/x-director" +"ccxml", "application/ccxml+xml" +"cdbcmsg", "application/vnd.contact.cmsg" +"cdf", "application/x-netcdf" +"cdkey", "application/vnd.mediastation.cdkey" +"cdmia", "application/cdmi-capability" +"cdmic", "application/cdmi-container" +"cdmid", "application/cdmi-domain" +"cdmio", "application/cdmi-object" +"cdmiq", "application/cdmi-queue" +"cdx", "chemical/x-cdx" +"cdxml", "application/vnd.chemdraw+xml" +"cdy", "application/vnd.cinderella" +"cer", "application/pkix-cert" +"cfs", "application/x-cfs-compressed" +"cgm", "image/cgm" +"chat", "application/x-chat" +"chm", "application/vnd.ms-htmlhelp" +"chrt", "application/vnd.kde.kchart" +"cif", "chemical/x-cif" +"cii", "application/vnd.anser-web-certificate-issue-initiation" +"cil", "application/vnd.ms-artgalry" +"cla", "application/vnd.claymore" +"class", "application/java-vm" +"clkk", "application/vnd.crick.clicker.keyboard" +"clkp", "application/vnd.crick.clicker.palette" +"clkt", "application/vnd.crick.clicker.template" +"clkw", "application/vnd.crick.clicker.wordbank" +"clkx", "application/vnd.crick.clicker" +"clp", "application/x-msclip" +"cmc", "application/vnd.cosmocaller" +"cmdf", "chemical/x-cmdf" +"cml", "chemical/x-cml" +"cmp", "application/vnd.yellowriver-custom-menu" +"cmx", "image/x-cmx" +"cod", "application/vnd.rim.cod" +"com", "application/x-msdownload" +"conf", "text/plain" +"cpio", "application/x-cpio" +"cpp", "text/x-c" +"cpt", "application/mac-compactpro" +"crd", "application/x-mscardfile" +"crl", "application/pkix-crl" +"crt", "application/x-x509-ca-cert" +"cryptonote", "application/vnd.rig.cryptonote" +"csh", "application/x-csh" +"csml", "chemical/x-csml" +"csp", "application/vnd.commonspace" +"css", "text/css" +"cst", "application/x-director" +"csv", "text/csv" +"cu", "application/cu-seeme" +"curl", "text/vnd.curl" +"cww", "application/prs.cww" +"cxt", "application/x-director" +"cxx", "text/x-c" +"dae", "model/vnd.collada+xml" +"daf", "application/vnd.mobius.daf" +"dart", "application/vnd.dart" +"dataless", "application/vnd.fdsn.seed" +"davmount", "application/davmount+xml" +"dbk", "application/docbook+xml" +"dcr", "application/x-director" +"dcurl", "text/vnd.curl.dcurl" +"dd2", "application/vnd.oma.dd2+xml" +"ddd", "application/vnd.fujixerox.ddd" +"deb", "application/x-debian-package" +"def", "text/plain" +"deploy", "application/octet-stream" +"der", "application/x-x509-ca-cert" +"dfac", "application/vnd.dreamfactory" +"dgc", "application/x-dgc-compressed" +"dic", "text/x-c" +"dir", "application/x-director" +"dis", "application/vnd.mobius.dis" +"dist", "application/octet-stream" +"distz", "application/octet-stream" +"djv", "image/vnd.djvu" +"djvu", "image/vnd.djvu" +"dll", "application/x-msdownload" +"dmg", "application/x-apple-diskimage" +"dmp", "application/vnd.tcpdump.pcap" +"dms", "application/octet-stream" +"dna", "application/vnd.dna" +"doc", "application/msword" +"docm", "application/vnd.ms-word.document.macroenabled.12" +"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" +"dot", "application/msword" +"dotm", "application/vnd.ms-word.template.macroenabled.12" +"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template" +"dp", "application/vnd.osgi.dp" +"dpg", "application/vnd.dpgraph" +"dra", "audio/vnd.dra" +"dsc", "text/prs.lines.tag" +"dssc", "application/dssc+der" +"dtb", "application/x-dtbook+xml" +"dtd", "application/xml-dtd" +"dts", "audio/vnd.dts" +"dtshd", "audio/vnd.dts.hd" +"dump", "application/octet-stream" +"dvb", "video/vnd.dvb.file" +"dvi", "application/x-dvi" +"dwf", "model/vnd.dwf" +"dwg", "image/vnd.dwg" +"dxf", "image/vnd.dxf" +"dxp", "application/vnd.spotfire.dxp" +"dxr", "application/x-director" +"ecelp4800", "audio/vnd.nuera.ecelp4800" +"ecelp7470", "audio/vnd.nuera.ecelp7470" +"ecelp9600", "audio/vnd.nuera.ecelp9600" +"ecma", "application/ecmascript" +"edm", "application/vnd.novadigm.edm" +"edx", "application/vnd.novadigm.edx" +"efif", "application/vnd.picsel" +"ei6", "application/vnd.pg.osasli" +"elc", "application/octet-stream" +"emf", "application/x-msmetafile" +"eml", "message/rfc822" +"emma", "application/emma+xml" +"emz", "application/x-msmetafile" +"eol", "audio/vnd.digital-winds" +"eot", "application/vnd.ms-fontobject" +"eps", "application/postscript" +"epub", "application/epub+zip" +"es3", "application/vnd.eszigno3+xml" +"esa", "application/vnd.osgi.subsystem" +"esf", "application/vnd.epson.esf" +"et3", "application/vnd.eszigno3+xml" +"etx", "text/x-setext" +"eva", "application/x-eva" +"evy", "application/x-envoy" +"exe", "application/x-msdownload" +"exi", "application/exi" +"ext", "application/vnd.novadigm.ext" +"ez", "application/andrew-inset" +"ez2", "application/vnd.ezpix-album" +"ez3", "application/vnd.ezpix-package" +"f", "text/x-fortran" +"f4v", "video/x-f4v" +"f77", "text/x-fortran" +"f90", "text/x-fortran" +"fbs", "image/vnd.fastbidsheet" +"fcdt", "application/vnd.adobe.formscentral.fcdt" +"fcs", "application/vnd.isac.fcs" +"fdf", "application/vnd.fdf" +"fe_launch", "application/vnd.denovo.fcselayout-link" +"fg5", "application/vnd.fujitsu.oasysgp" +"fgd", "application/x-director" +"fh", "image/x-freehand" +"fh4", "image/x-freehand" +"fh5", "image/x-freehand" +"fh7", "image/x-freehand" +"fhc", "image/x-freehand" +"fig", "application/x-xfig" +"flac", "audio/x-flac" +"fli", "video/x-fli" +"flo", "application/vnd.micrografx.flo" +"flv", "video/x-flv" +"flw", "application/vnd.kde.kivio" +"flx", "text/vnd.fmi.flexstor" +"fly", "text/vnd.fly" +"fm", "application/vnd.framemaker" +"fnc", "application/vnd.frogans.fnc" +"for", "text/x-fortran" +"fpx", "image/vnd.fpx" +"frame", "application/vnd.framemaker" +"fsc", "application/vnd.fsc.weblaunch" +"fst", "image/vnd.fst" +"ftc", "application/vnd.fluxtime.clip" +"fti", "application/vnd.anser-web-funds-transfer-initiation" +"fvt", "video/vnd.fvt" +"fxp", "application/vnd.adobe.fxp" +"fxpl", "application/vnd.adobe.fxp" +"fzs", "application/vnd.fuzzysheet" +"g2w", "application/vnd.geoplan" +"g3", "image/g3fax" +"g3w", "application/vnd.geospace" +"gac", "application/vnd.groove-account" +"gam", "application/x-tads" +"gbr", "application/rpki-ghostbusters" +"gca", "application/x-gca-compressed" +"gdl", "model/vnd.gdl" +"geo", "application/vnd.dynageo" +"gex", "application/vnd.geometry-explorer" +"ggb", "application/vnd.geogebra.file" +"ggt", "application/vnd.geogebra.tool" +"ghf", "application/vnd.groove-help" +"gif", "image/gif" +"gim", "application/vnd.groove-identity-message" +"gml", "application/gml+xml" +"gmx", "application/vnd.gmx" +"gnumeric", "application/x-gnumeric" +"gph", "application/vnd.flographit" +"gpx", "application/gpx+xml" +"gqf", "application/vnd.grafeq" +"gqs", "application/vnd.grafeq" +"gram", "application/srgs" +"gramps", "application/x-gramps-xml" +"gre", "application/vnd.geometry-explorer" +"grv", "application/vnd.groove-injector" +"grxml", "application/srgs+xml" +"gsf", "application/x-font-ghostscript" +"gtar", "application/x-gtar" +"gtm", "application/vnd.groove-tool-message" +"gtw", "model/vnd.gtw" +"gv", "text/vnd.graphviz" +"gxf", "application/gxf" +"gxt", "application/vnd.geonext" +"h", "text/x-c" +"h261", "video/h261" +"h263", "video/h263" +"h264", "video/h264" +"hal", "application/vnd.hal+xml" +"hbci", "application/vnd.hbci" +"hdf", "application/x-hdf" +"hh", "text/x-c" +"hlp", "application/winhlp" +"hpgl", "application/vnd.hp-hpgl" +"hpid", "application/vnd.hp-hpid" +"hps", "application/vnd.hp-hps" +"hqx", "application/mac-binhex40" +"htke", "application/vnd.kenameaapp" +"htm", "text/html" +"html", "text/html" +"hvd", "application/vnd.yamaha.hv-dic" +"hvp", "application/vnd.yamaha.hv-voice" +"hvs", "application/vnd.yamaha.hv-script" +"i2g", "application/vnd.intergeo" +"icc", "application/vnd.iccprofile" +"ice", "x-conference/x-cooltalk" +"icm", "application/vnd.iccprofile" +"ico", "image/x-icon" +"ics", "text/calendar" +"ief", "image/ief" +"ifb", "text/calendar" +"ifm", "application/vnd.shana.informed.formdata" +"iges", "model/iges" +"igl", "application/vnd.igloader" +"igm", "application/vnd.insors.igm" +"igs", "model/iges" +"igx", "application/vnd.micrografx.igx" +"iif", "application/vnd.shana.informed.interchange" +"imp", "application/vnd.accpac.simply.imp" +"ims", "application/vnd.ms-ims" +"in", "text/plain" +"ink", "application/inkml+xml" +"inkml", "application/inkml+xml" +"install", "application/x-install-instructions" +"iota", "application/vnd.astraea-software.iota" +"ipfix", "application/ipfix" +"ipk", "application/vnd.shana.informed.package" +"irm", "application/vnd.ibm.rights-management" +"irp", "application/vnd.irepository.package+xml" +"iso", "application/x-iso9660-image" +"itp", "application/vnd.shana.informed.formtemplate" +"ivp", "application/vnd.immervision-ivp" +"ivu", "application/vnd.immervision-ivu" +"jad", "text/vnd.sun.j2me.app-descriptor" +"jam", "application/vnd.jam" +"jar", "application/java-archive" +"java", "text/x-java-source" +"jisp", "application/vnd.jisp" +"jlt", "application/vnd.hp-jlyt" +"jnlp", "application/x-java-jnlp-file" +"joda", "application/vnd.joost.joda-archive" +"jpe", "image/jpeg" +"jpeg", "image/jpeg" +"jpg", "image/jpeg" +"jpgm", "video/jpm" +"jpgv", "video/jpeg" +"jpm", "video/jpm" +"js", "application/javascript" +"json", "application/json" +"jsonml", "application/jsonml+json" +"kar", "audio/midi" +"karbon", "application/vnd.kde.karbon" +"kfo", "application/vnd.kde.kformula" +"kia", "application/vnd.kidspiration" +"kml", "application/vnd.google-earth.kml+xml" +"kmz", "application/vnd.google-earth.kmz" +"kne", "application/vnd.kinar" +"knp", "application/vnd.kinar" +"kon", "application/vnd.kde.kontour" +"kpr", "application/vnd.kde.kpresenter" +"kpt", "application/vnd.kde.kpresenter" +"kpxx", "application/vnd.ds-keypoint" +"ksp", "application/vnd.kde.kspread" +"ktr", "application/vnd.kahootz" +"ktx", "image/ktx" +"ktz", "application/vnd.kahootz" +"kwd", "application/vnd.kde.kword" +"kwt", "application/vnd.kde.kword" +"lasxml", "application/vnd.las.las+xml" +"latex", "application/x-latex" +"lbd", "application/vnd.llamagraphics.life-balance.desktop" +"lbe", "application/vnd.llamagraphics.life-balance.exchange+xml" +"les", "application/vnd.hhe.lesson-player" +"lha", "application/x-lzh-compressed" +"link66", "application/vnd.route66.link66+xml" +"list", "text/plain" +"list3820", "application/vnd.ibm.modcap" +"listafp", "application/vnd.ibm.modcap" +"lnk", "application/x-ms-shortcut" +"log", "text/plain" +"lostxml", "application/lost+xml" +"lrf", "application/octet-stream" +"lrm", "application/vnd.ms-lrm" +"ltf", "application/vnd.frogans.ltf" +"lvp", "audio/vnd.lucent.voice" +"lwp", "application/vnd.lotus-wordpro" +"lzh", "application/x-lzh-compressed" +"m13", "application/x-msmediaview" +"m14", "application/x-msmediaview" +"m1v", "video/mpeg" +"m21", "application/mp21" +"m2a", "audio/mpeg" +"m2v", "video/mpeg" +"m3a", "audio/mpeg" +"m3u", "audio/x-mpegurl" +"m3u8", "application/vnd.apple.mpegurl" +"m4u", "video/vnd.mpegurl" +"m4v", "video/x-m4v" +"ma", "application/mathematica" +"mads", "application/mads+xml" +"mag", "application/vnd.ecowin.chart" +"maker", "application/vnd.framemaker" +"man", "text/troff" +"mar", "application/octet-stream" +"mathml", "application/mathml+xml" +"mb", "application/mathematica" +"mbk", "application/vnd.mobius.mbk" +"mbox", "application/mbox" +"mc1", "application/vnd.medcalcdata" +"mcd", "application/vnd.mcd" +"mcurl", "text/vnd.curl.mcurl" +"mdb", "application/x-msaccess" +"mdi", "image/vnd.ms-modi" +"me", "text/troff" +"mesh", "model/mesh" +"meta4", "application/metalink4+xml" +"metalink", "application/metalink+xml" +"mets", "application/mets+xml" +"mfm", "application/vnd.mfmp" +"mft", "application/rpki-manifest" +"mgp", "application/vnd.osgeo.mapguide.package" +"mgz", "application/vnd.proteus.magazine" +"mid", "audio/midi" +"midi", "audio/midi" +"mie", "application/x-mie" +"mif", "application/vnd.mif" +"mime", "message/rfc822" +"mj2", "video/mj2" +"mjp2", "video/mj2" +"mk3d", "video/x-matroska" +"mka", "audio/x-matroska" +"mks", "video/x-matroska" +"mkv", "video/x-matroska" +"mlp", "application/vnd.dolby.mlp" +"mmd", "application/vnd.chipnuts.karaoke-mmd" +"mmf", "application/vnd.smaf" +"mmr", "image/vnd.fujixerox.edmics-mmr" +"mng", "video/x-mng" +"mny", "application/x-msmoney" +"mobi", "application/x-mobipocket-ebook" +"mods", "application/mods+xml" +"mov", "video/quicktime" +"movie", "video/x-sgi-movie" +"mp2", "audio/mpeg" +"mp21", "application/mp21" +"mp2a", "audio/mpeg" +"mp3", "audio/mpeg" +"mp4", "video/mp4" +"mp4a", "audio/mp4" +"mp4s", "application/mp4" +"mp4v", "video/mp4" +"mpc", "application/vnd.mophun.certificate" +"mpe", "video/mpeg" +"mpeg", "video/mpeg" +"mpg", "video/mpeg" +"mpg4", "video/mp4" +"mpga", "audio/mpeg" +"mpkg", "application/vnd.apple.installer+xml" +"mpm", "application/vnd.blueice.multipass" +"mpn", "application/vnd.mophun.application" +"mpp", "application/vnd.ms-project" +"mpt", "application/vnd.ms-project" +"mpy", "application/vnd.ibm.minipay" +"mqy", "application/vnd.mobius.mqy" +"mrc", "application/marc" +"mrcx", "application/marcxml+xml" +"ms", "text/troff" +"mscml", "application/mediaservercontrol+xml" +"mseed", "application/vnd.fdsn.mseed" +"mseq", "application/vnd.mseq" +"msf", "application/vnd.epson.msf" +"msh", "model/mesh" +"msi", "application/x-msdownload" +"msl", "application/vnd.mobius.msl" +"msty", "application/vnd.muvee.style" +"mts", "model/vnd.mts" +"mus", "application/vnd.musician" +"musicxml", "application/vnd.recordare.musicxml+xml" +"mvb", "application/x-msmediaview" +"mwf", "application/vnd.mfer" +"mxf", "application/mxf" +"mxl", "application/vnd.recordare.musicxml" +"mxml", "application/xv+xml" +"mxs", "application/vnd.triscape.mxs" +"mxu", "video/vnd.mpegurl" +"n-gage", "application/vnd.nokia.n-gage.symbian.install" +"n3", "text/n3" +"nb", "application/mathematica" +"nbp", "application/vnd.wolfram.player" +"nc", "application/x-netcdf" +"ncx", "application/x-dtbncx+xml" +"nfo", "text/x-nfo" +"ngdat", "application/vnd.nokia.n-gage.data" +"nitf", "application/vnd.nitf" +"nlu", "application/vnd.neurolanguage.nlu" +"nml", "application/vnd.enliven" +"nnd", "application/vnd.noblenet-directory" +"nns", "application/vnd.noblenet-sealer" +"nnw", "application/vnd.noblenet-web" +"npx", "image/vnd.net-fpx" +"nsc", "application/x-conference" +"nsf", "application/vnd.lotus-notes" +"ntf", "application/vnd.nitf" +"nzb", "application/x-nzb" +"oa2", "application/vnd.fujitsu.oasys2" +"oa3", "application/vnd.fujitsu.oasys3" +"oas", "application/vnd.fujitsu.oasys" +"obd", "application/x-msbinder" +"obj", "application/x-tgif" +"oda", "application/oda" +"odb", "application/vnd.oasis.opendocument.database" +"odc", "application/vnd.oasis.opendocument.chart" +"odf", "application/vnd.oasis.opendocument.formula" +"odft", "application/vnd.oasis.opendocument.formula-template" +"odg", "application/vnd.oasis.opendocument.graphics" +"odi", "application/vnd.oasis.opendocument.image" +"odm", "application/vnd.oasis.opendocument.text-master" +"odp", "application/vnd.oasis.opendocument.presentation" +"ods", "application/vnd.oasis.opendocument.spreadsheet" +"odt", "application/vnd.oasis.opendocument.text" +"oga", "audio/ogg" +"ogg", "audio/ogg" +"ogv", "video/ogg" +"ogx", "application/ogg" +"omdoc", "application/omdoc+xml" +"onepkg", "application/onenote" +"onetmp", "application/onenote" +"onetoc", "application/onenote" +"onetoc2", "application/onenote" +"opf", "application/oebps-package+xml" +"opml", "text/x-opml" +"oprc", "application/vnd.palm" +"org", "application/vnd.lotus-organizer" +"osf", "application/vnd.yamaha.openscoreformat" +"osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml" +"otc", "application/vnd.oasis.opendocument.chart-template" +"otf", "application/x-font-otf" +"otg", "application/vnd.oasis.opendocument.graphics-template" +"oth", "application/vnd.oasis.opendocument.text-web" +"oti", "application/vnd.oasis.opendocument.image-template" +"otp", "application/vnd.oasis.opendocument.presentation-template" +"ots", "application/vnd.oasis.opendocument.spreadsheet-template" +"ott", "application/vnd.oasis.opendocument.text-template" +"oxps", "application/oxps" +"oxt", "application/vnd.openofficeorg.extension" +"p", "text/x-pascal" +"p10", "application/pkcs10" +"p12", "application/x-pkcs12" +"p7b", "application/x-pkcs7-certificates" +"p7c", "application/pkcs7-mime" +"p7m", "application/pkcs7-mime" +"p7r", "application/x-pkcs7-certreqresp" +"p7s", "application/pkcs7-signature" +"p8", "application/pkcs8" +"pas", "text/x-pascal" +"paw", "application/vnd.pawaafile" +"pbd", "application/vnd.powerbuilder6" +"pbm", "image/x-portable-bitmap" +"pcap", "application/vnd.tcpdump.pcap" +"pcf", "application/x-font-pcf" +"pcl", "application/vnd.hp-pcl" +"pclxl", "application/vnd.hp-pclxl" +"pct", "image/x-pict" +"pcurl", "application/vnd.curl.pcurl" +"pcx", "image/x-pcx" +"pdb", "application/vnd.palm" +"pdf", "application/pdf" +"pfa", "application/x-font-type1" +"pfb", "application/x-font-type1" +"pfm", "application/x-font-type1" +"pfr", "application/font-tdpfr" +"pfx", "application/x-pkcs12" +"pgm", "image/x-portable-graymap" +"pgn", "application/x-chess-pgn" +"pgp", "application/pgp-encrypted" +"pic", "image/x-pict" +"pkg", "application/octet-stream" +"pki", "application/pkixcmp" +"pkipath", "application/pkix-pkipath" +"plb", "application/vnd.3gpp.pic-bw-large" +"plc", "application/vnd.mobius.plc" +"plf", "application/vnd.pocketlearn" +"pls", "application/pls+xml" +"pml", "application/vnd.ctc-posml" +"png", "image/png" +"pnm", "image/x-portable-anymap" +"portpkg", "application/vnd.macports.portpkg" +"pot", "application/vnd.ms-powerpoint" +"potm", "application/vnd.ms-powerpoint.template.macroenabled.12" +"potx", "application/vnd.openxmlformats-officedocument.presentationml.template" +"ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12" +"ppd", "application/vnd.cups-ppd" +"ppm", "image/x-portable-pixmap" +"pps", "application/vnd.ms-powerpoint" +"ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12" +"ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow" +"ppt", "application/vnd.ms-powerpoint" +"pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12" +"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" +"pqa", "application/vnd.palm" +"prc", "application/x-mobipocket-ebook" +"pre", "application/vnd.lotus-freelance" +"prf", "application/pics-rules" +"ps", "application/postscript" +"psb", "application/vnd.3gpp.pic-bw-small" +"psd", "image/vnd.adobe.photoshop" +"psf", "application/x-font-linux-psf" +"pskcxml", "application/pskc+xml" +"ptid", "application/vnd.pvi.ptid1" +"pub", "application/x-mspublisher" +"pvb", "application/vnd.3gpp.pic-bw-var" +"pwn", "application/vnd.3m.post-it-notes" +"pya", "audio/vnd.ms-playready.media.pya" +"pyv", "video/vnd.ms-playready.media.pyv" +"qam", "application/vnd.epson.quickanime" +"qbo", "application/vnd.intu.qbo" +"qfx", "application/vnd.intu.qfx" +"qps", "application/vnd.publishare-delta-tree" +"qt", "video/quicktime" +"qwd", "application/vnd.quark.quarkxpress" +"qwt", "application/vnd.quark.quarkxpress" +"qxb", "application/vnd.quark.quarkxpress" +"qxd", "application/vnd.quark.quarkxpress" +"qxl", "application/vnd.quark.quarkxpress" +"qxt", "application/vnd.quark.quarkxpress" +"ra", "audio/x-pn-realaudio" +"ram", "audio/x-pn-realaudio" +"rar", "application/x-rar-compressed" +"ras", "image/x-cmu-raster" +"rcprofile", "application/vnd.ipunplugged.rcprofile" +"rdf", "application/rdf+xml" +"rdz", "application/vnd.data-vision.rdz" +"rep", "application/vnd.businessobjects" +"res", "application/x-dtbresource+xml" +"rgb", "image/x-rgb" +"rif", "application/reginfo+xml" +"rip", "audio/vnd.rip" +"ris", "application/x-research-info-systems" +"rl", "application/resource-lists+xml" +"rlc", "image/vnd.fujixerox.edmics-rlc" +"rld", "application/resource-lists-diff+xml" +"rm", "application/vnd.rn-realmedia" +"rmi", "audio/midi" +"rmp", "audio/x-pn-realaudio-plugin" +"rms", "application/vnd.jcp.javame.midlet-rms" +"rmvb", "application/vnd.rn-realmedia-vbr" +"rnc", "application/relax-ng-compact-syntax" +"roa", "application/rpki-roa" +"roff", "text/troff" +"rp9", "application/vnd.cloanto.rp9" +"rpss", "application/vnd.nokia.radio-presets" +"rpst", "application/vnd.nokia.radio-preset" +"rq", "application/sparql-query" +"rs", "application/rls-services+xml" +"rsd", "application/rsd+xml" +"rss", "application/rss+xml" +"rtf", "application/rtf" +"rtx", "text/richtext" +"s", "text/x-asm" +"s3m", "audio/s3m" +"saf", "application/vnd.yamaha.smaf-audio" +"sbml", "application/sbml+xml" +"sc", "application/vnd.ibm.secure-container" +"scd", "application/x-msschedule" +"scm", "application/vnd.lotus-screencam" +"scq", "application/scvp-cv-request" +"scs", "application/scvp-cv-response" +"scurl", "text/vnd.curl.scurl" +"sda", "application/vnd.stardivision.draw" +"sdc", "application/vnd.stardivision.calc" +"sdd", "application/vnd.stardivision.impress" +"sdkd", "application/vnd.solent.sdkm+xml" +"sdkm", "application/vnd.solent.sdkm+xml" +"sdp", "application/sdp" +"sdw", "application/vnd.stardivision.writer" +"see", "application/vnd.seemail" +"seed", "application/vnd.fdsn.seed" +"sema", "application/vnd.sema" +"semd", "application/vnd.semd" +"semf", "application/vnd.semf" +"ser", "application/java-serialized-object" +"setpay", "application/set-payment-initiation" +"setreg", "application/set-registration-initiation" +"sfd-hdstx", "application/vnd.hydrostatix.sof-data" +"sfs", "application/vnd.spotfire.sfs" +"sfv", "text/x-sfv" +"sgi", "image/sgi" +"sgl", "application/vnd.stardivision.writer-global" +"sgm", "text/sgml" +"sgml", "text/sgml" +"sh", "application/x-sh" +"shar", "application/x-shar" +"shf", "application/shf+xml" +"sid", "image/x-mrsid-image" +"sig", "application/pgp-signature" +"sil", "audio/silk" +"silo", "model/mesh" +"sis", "application/vnd.symbian.install" +"sisx", "application/vnd.symbian.install" +"sit", "application/x-stuffit" +"sitx", "application/x-stuffitx" +"skd", "application/vnd.koan" +"skm", "application/vnd.koan" +"skp", "application/vnd.koan" +"skt", "application/vnd.koan" +"sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12" +"sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide" +"slt", "application/vnd.epson.salt" +"sm", "application/vnd.stepmania.stepchart" +"smf", "application/vnd.stardivision.math" +"smi", "application/smil+xml" +"smil", "application/smil+xml" +"smv", "video/x-smv" +"smzip", "application/vnd.stepmania.package" +"snd", "audio/basic" +"snf", "application/x-font-snf" +"so", "application/octet-stream" +"spc", "application/x-pkcs7-certificates" +"spf", "application/vnd.yamaha.smaf-phrase" +"spl", "application/x-futuresplash" +"spot", "text/vnd.in3d.spot" +"spp", "application/scvp-vp-response" +"spq", "application/scvp-vp-request" +"spx", "audio/ogg" +"sql", "application/x-sql" +"src", "application/x-wais-source" +"srt", "application/x-subrip" +"sru", "application/sru+xml" +"srx", "application/sparql-results+xml" +"ssdl", "application/ssdl+xml" +"sse", "application/vnd.kodak-descriptor" +"ssf", "application/vnd.epson.ssf" +"ssml", "application/ssml+xml" +"st", "application/vnd.sailingtracker.track" +"stc", "application/vnd.sun.xml.calc.template" +"std", "application/vnd.sun.xml.draw.template" +"stf", "application/vnd.wt.stf" +"sti", "application/vnd.sun.xml.impress.template" +"stk", "application/hyperstudio" +"stl", "application/vnd.ms-pki.stl" +"str", "application/vnd.pg.format" +"stw", "application/vnd.sun.xml.writer.template" +"sub", "image/vnd.dvb.subtitle" +"sus", "application/vnd.sus-calendar" +"susp", "application/vnd.sus-calendar" +"sv4cpio", "application/x-sv4cpio" +"sv4crc", "application/x-sv4crc" +"svc", "application/vnd.dvb.service" +"svd", "application/vnd.svd" +"svg", "image/svg+xml" +"svgz", "image/svg+xml" +"swa", "application/x-director" +"swf", "application/x-shockwave-flash" +"swi", "application/vnd.aristanetworks.swi" +"sxc", "application/vnd.sun.xml.calc" +"sxd", "application/vnd.sun.xml.draw" +"sxg", "application/vnd.sun.xml.writer.global" +"sxi", "application/vnd.sun.xml.impress" +"sxm", "application/vnd.sun.xml.math" +"sxw", "application/vnd.sun.xml.writer" +"t", "text/troff" +"t3", "application/x-t3vm-image" +"taglet", "application/vnd.mynfc" +"tao", "application/vnd.tao.intent-module-archive" +"tar", "application/x-tar" +"tcap", "application/vnd.3gpp2.tcap" +"tcl", "application/x-tcl" +"teacher", "application/vnd.smart.teacher" +"tei", "application/tei+xml" +"teicorpus", "application/tei+xml" +"tex", "application/x-tex" +"texi", "application/x-texinfo" +"texinfo", "application/x-texinfo" +"text", "text/plain" +"tfi", "application/thraud+xml" +"tfm", "application/x-tex-tfm" +"tga", "image/x-tga" +"thmx", "application/vnd.ms-officetheme" +"tif", "image/tiff" +"tiff", "image/tiff" +"tmo", "application/vnd.tmobile-livetv" +"torrent", "application/x-bittorrent" +"tpl", "application/vnd.groove-tool-template" +"tpt", "application/vnd.trid.tpt" +"tr", "text/troff" +"tra", "application/vnd.trueapp" +"trm", "application/x-msterminal" +"tsd", "application/timestamped-data" +"tsv", "text/tab-separated-values" +"ttc", "application/x-font-ttf" +"ttf", "application/x-font-ttf" +"ttl", "text/turtle" +"twd", "application/vnd.simtech-mindmapper" +"twds", "application/vnd.simtech-mindmapper" +"txd", "application/vnd.genomatix.tuxedo" +"txf", "application/vnd.mobius.txf" +"txt", "text/plain" +"u32", "application/x-authorware-bin" +"udeb", "application/x-debian-package" +"ufd", "application/vnd.ufdl" +"ufdl", "application/vnd.ufdl" +"ulx", "application/x-glulx" +"umj", "application/vnd.umajin" +"unityweb", "application/vnd.unity" +"uoml", "application/vnd.uoml+xml" +"uri", "text/uri-list" +"uris", "text/uri-list" +"urls", "text/uri-list" +"ustar", "application/x-ustar" +"utz", "application/vnd.uiq.theme" +"uu", "text/x-uuencode" +"uva", "audio/vnd.dece.audio" +"uvd", "application/vnd.dece.data" +"uvf", "application/vnd.dece.data" +"uvg", "image/vnd.dece.graphic" +"uvh", "video/vnd.dece.hd" +"uvi", "image/vnd.dece.graphic" +"uvm", "video/vnd.dece.mobile" +"uvp", "video/vnd.dece.pd" +"uvs", "video/vnd.dece.sd" +"uvt", "application/vnd.dece.ttml+xml" +"uvu", "video/vnd.uvvu.mp4" +"uvv", "video/vnd.dece.video" +"uvva", "audio/vnd.dece.audio" +"uvvd", "application/vnd.dece.data" +"uvvf", "application/vnd.dece.data" +"uvvg", "image/vnd.dece.graphic" +"uvvh", "video/vnd.dece.hd" +"uvvi", "image/vnd.dece.graphic" +"uvvm", "video/vnd.dece.mobile" +"uvvp", "video/vnd.dece.pd" +"uvvs", "video/vnd.dece.sd" +"uvvt", "application/vnd.dece.ttml+xml" +"uvvu", "video/vnd.uvvu.mp4" +"uvvv", "video/vnd.dece.video" +"uvvx", "application/vnd.dece.unspecified" +"uvvz", "application/vnd.dece.zip" +"uvx", "application/vnd.dece.unspecified" +"uvz", "application/vnd.dece.zip" +"vcard", "text/vcard" +"vcd", "application/x-cdlink" +"vcf", "text/x-vcard" +"vcg", "application/vnd.groove-vcard" +"vcs", "text/x-vcalendar" +"vcx", "application/vnd.vcx" +"vis", "application/vnd.visionary" +"viv", "video/vnd.vivo" +"vob", "video/x-ms-vob" +"vor", "application/vnd.stardivision.writer" +"vox", "application/x-authorware-bin" +"vrml", "model/vrml" +"vsd", "application/vnd.visio" +"vsf", "application/vnd.vsf" +"vss", "application/vnd.visio" +"vst", "application/vnd.visio" +"vsw", "application/vnd.visio" +"vtu", "model/vnd.vtu" +"vxml", "application/voicexml+xml" +"w3d", "application/x-director" +"wad", "application/x-doom" +"wav", "audio/x-wav" +"wax", "audio/x-ms-wax" +"wbmp", "image/vnd.wap.wbmp" +"wbs", "application/vnd.criticaltools.wbs+xml" +"wbxml", "application/vnd.wap.wbxml" +"wcm", "application/vnd.ms-works" +"wdb", "application/vnd.ms-works" +"wdp", "image/vnd.ms-photo" +"weba", "audio/webm" +"webm", "video/webm" +"webp", "image/webp" +"wg", "application/vnd.pmi.widget" +"wgt", "application/widget" +"wks", "application/vnd.ms-works" +"wm", "video/x-ms-wm" +"wma", "audio/x-ms-wma" +"wmd", "application/x-ms-wmd" +"wmf", "application/x-msmetafile" +"wml", "text/vnd.wap.wml" +"wmlc", "application/vnd.wap.wmlc" +"wmls", "text/vnd.wap.wmlscript" +"wmlsc", "application/vnd.wap.wmlscriptc" +"wmv", "video/x-ms-wmv" +"wmx", "video/x-ms-wmx" +"wmz", "application/x-ms-wmz" +"woff", "application/font-woff" +"wpd", "application/vnd.wordperfect" +"wpl", "application/vnd.ms-wpl" +"wps", "application/vnd.ms-works" +"wqd", "application/vnd.wqd" +"wri", "application/x-mswrite" +"wrl", "model/vrml" +"wsdl", "application/wsdl+xml" +"wspolicy", "application/wspolicy+xml" +"wtb", "application/vnd.webturbo" +"wvx", "video/x-ms-wvx" +"x32", "application/x-authorware-bin" +"x3d", "model/x3d+xml" +"x3db", "model/x3d+binary" +"x3dbz", "model/x3d+binary" +"x3dv", "model/x3d+vrml" +"x3dvz", "model/x3d+vrml" +"x3dz", "model/x3d+xml" +"xaml", "application/xaml+xml" +"xap", "application/x-silverlight-app" +"xar", "application/vnd.xara" +"xbap", "application/x-ms-xbap" +"xbd", "application/vnd.fujixerox.docuworks.binder" +"xbm", "image/x-xbitmap" +"xdf", "application/xcap-diff+xml" +"xdm", "application/vnd.syncml.dm+xml" +"xdp", "application/vnd.adobe.xdp+xml" +"xdssc", "application/dssc+xml" +"xdw", "application/vnd.fujixerox.docuworks" +"xenc", "application/xenc+xml" +"xer", "application/patch-ops-error+xml" +"xfdf", "application/vnd.adobe.xfdf" +"xfdl", "application/vnd.xfdl" +"xht", "application/xhtml+xml" +"xhtml", "application/xhtml+xml" +"xhvml", "application/xv+xml" +"xif", "image/vnd.xiff" +"xla", "application/vnd.ms-excel" +"xlam", "application/vnd.ms-excel.addin.macroenabled.12" +"xlc", "application/vnd.ms-excel" +"xlf", "application/x-xliff+xml" +"xlm", "application/vnd.ms-excel" +"xls", "application/vnd.ms-excel" +"xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12" +"xlsm", "application/vnd.ms-excel.sheet.macroenabled.12" +"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" +"xlt", "application/vnd.ms-excel" +"xltm", "application/vnd.ms-excel.template.macroenabled.12" +"xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template" +"xlw", "application/vnd.ms-excel" +"xm", "audio/xm" +"xml", "application/xml" +"xo", "application/vnd.olpc-sugar" +"xop", "application/xop+xml" +"xpi", "application/x-xpinstall" +"xpl", "application/xproc+xml" +"xpm", "image/x-xpixmap" +"xpr", "application/vnd.is-xpr" +"xps", "application/vnd.ms-xpsdocument" +"xpw", "application/vnd.intercon.formnet" +"xpx", "application/vnd.intercon.formnet" +"xsl", "application/xml" +"xslt", "application/xslt+xml" +"xsm", "application/vnd.syncml+xml" +"xspf", "application/xspf+xml" +"xul", "application/vnd.mozilla.xul+xml" +"xvm", "application/xv+xml" +"xvml", "application/xv+xml" +"xwd", "image/x-xwindowdump" +"xyz", "chemical/x-xyz" +"xz", "application/x-xz" +"yang", "application/yang" +"yin", "application/yin+xml" +"z1", "application/x-zmachine" +"z2", "application/x-zmachine" +"z3", "application/x-zmachine" +"z4", "application/x-zmachine" +"z5", "application/x-zmachine" +"z6", "application/x-zmachine" +"z7", "application/x-zmachine" +"z8", "application/x-zmachine" +"zaz", "application/vnd.zzazz.deck+xml" +"zip", "application/zip" +"zir", "application/vnd.zul" +"zirz", "application/vnd.zul" +"zmm", "application/vnd.handheld-entertainment+xml" +%% +const char *extension_to_mime_type(const char *extension, size_t extension_len) { + const auto &result = search_extension(extension, extension_len); + if (result == nullptr) { + return nullptr; + } + + return result->mime_type; +} diff --git a/submodules/ton/tonlib-src/tdutils/generate/auto/mime_type_to_extension.cpp b/submodules/ton/tonlib-src/tdutils/generate/auto/mime_type_to_extension.cpp new file mode 100644 index 00000000000..4934752ed90 --- /dev/null +++ b/submodules/ton/tonlib-src/tdutils/generate/auto/mime_type_to_extension.cpp @@ -0,0 +1,2850 @@ +/* ANSI-C code produced by gperf version 3.0.3 */ +/* Command-line: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/gperf -m100 auto/mime_type_to_extension.gperf */ +/* Computed positions: -k'1,7,9-10,13-18,20,23,25-26,31,36,$' */ + +#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \ + && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \ + && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \ + && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \ + && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \ + && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \ + && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \ + && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \ + && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \ + && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \ + && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \ + && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \ + && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \ + && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \ + && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \ + && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \ + && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \ + && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \ + && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \ + && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \ + && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \ + && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \ + && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126)) +/* The character set is not based on ISO-646. */ +#error "gperf generated tables don't work with this execution character set. Please report a bug to ." +#endif + +#line 12 "auto/mime_type_to_extension.gperf" +struct mime_type_and_extension { + const char *mime_type; + const char *extension; +}; +#include +/* maximum key range = 4097, duplicates = 0 */ + +#ifndef GPERF_DOWNCASE +#define GPERF_DOWNCASE 1 +static unsigned char gperf_downcase[256] = + { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, + 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, + 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, + 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, + 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, + 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, + 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, + 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, + 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, + 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, + 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, + 255 + }; +#endif + +#ifndef GPERF_CASE_STRCMP +#define GPERF_CASE_STRCMP 1 +static int +gperf_case_strcmp (register const char *s1, register const char *s2) +{ + for (;;) + { + unsigned char c1 = gperf_downcase[(unsigned char)*s1++]; + unsigned char c2 = gperf_downcase[(unsigned char)*s2++]; + if (c1 != 0 && c1 == c2) + continue; + return (int)c1 - (int)c2; + } +} +#endif + +#ifdef __GNUC__ +__inline +#else +#ifdef __cplusplus +inline +#endif +#endif +static unsigned int +mime_type_hash (register const char *str, register unsigned int len) +{ + static const unsigned short asso_values[] = + { + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 584, 4141, 169, 34, 63, 9, 11, + 109, 66, 18, 7, 10, 10, 7, 7, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 7, 995, 78, 18, 7, + 413, 507, 841, 8, 109, 1358, 363, 10, 7, 8, + 9, 46, 40, 11, 20, 583, 24, 1077, 253, 1558, + 149, 4141, 4141, 4141, 4141, 4141, 4141, 7, 995, 78, + 18, 7, 413, 507, 841, 8, 109, 1358, 363, 10, + 7, 8, 9, 46, 40, 11, 20, 583, 24, 1077, + 253, 1558, 149, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, 4141, + 4141, 4141, 4141, 4141, 4141, 4141 + }; + register unsigned int hval = len; + + switch (hval) + { + default: + hval += asso_values[(unsigned char)str[35]]; + /*FALLTHROUGH*/ + case 35: + case 34: + case 33: + case 32: + case 31: + hval += asso_values[(unsigned char)str[30]]; + /*FALLTHROUGH*/ + case 30: + case 29: + case 28: + case 27: + case 26: + hval += asso_values[(unsigned char)str[25]]; + /*FALLTHROUGH*/ + case 25: + hval += asso_values[(unsigned char)str[24]]; + /*FALLTHROUGH*/ + case 24: + case 23: + hval += asso_values[(unsigned char)str[22]]; + /*FALLTHROUGH*/ + case 22: + case 21: + case 20: + hval += asso_values[(unsigned char)str[19]]; + /*FALLTHROUGH*/ + case 19: + case 18: + hval += asso_values[(unsigned char)str[17]]; + /*FALLTHROUGH*/ + case 17: + hval += asso_values[(unsigned char)str[16]]; + /*FALLTHROUGH*/ + case 16: + hval += asso_values[(unsigned char)str[15]]; + /*FALLTHROUGH*/ + case 15: + hval += asso_values[(unsigned char)str[14]]; + /*FALLTHROUGH*/ + case 14: + hval += asso_values[(unsigned char)str[13]]; + /*FALLTHROUGH*/ + case 13: + hval += asso_values[(unsigned char)str[12]]; + /*FALLTHROUGH*/ + case 12: + case 11: + case 10: + hval += asso_values[(unsigned char)str[9]]; + /*FALLTHROUGH*/ + case 9: + hval += asso_values[(unsigned char)str[8]]; + /*FALLTHROUGH*/ + case 8: + case 7: + hval += asso_values[(unsigned char)str[6]]; + /*FALLTHROUGH*/ + case 6: + case 5: + case 4: + case 3: + case 2: + case 1: + hval += asso_values[(unsigned char)str[0]]; + break; + } + return hval + asso_values[(unsigned char)str[len - 1]]; +} + +const struct mime_type_and_extension * +search_mime_type (register const char *str, register unsigned int len) +{ + enum + { + TOTAL_KEYWORDS = 765, + MIN_WORD_LENGTH = 7, + MAX_WORD_LENGTH = 73, + MIN_HASH_VALUE = 44, + MAX_HASH_VALUE = 4140 + }; + + static const struct mime_type_and_extension wordlist[] = + { + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 652 "auto/mime_type_to_extension.gperf" + {"image/sgi", "sgi"}, + {"",nullptr}, {"",nullptr}, +#line 611 "auto/mime_type_to_extension.gperf" + {"audio/s3m", "s3m"}, + {"",nullptr}, {"",nullptr}, +#line 704 "auto/mime_type_to_extension.gperf" + {"text/css", "css"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 690 "auto/mime_type_to_extension.gperf" + {"model/iges", "igs"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 607 "auto/mime_type_to_extension.gperf" + {"audio/midi", "midi"}, +#line 608 "auto/mime_type_to_extension.gperf" + {"audio/mp4", "mp4a"}, +#line 705 "auto/mime_type_to_extension.gperf" + {"text/csv", "csv"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 750 "auto/mime_type_to_extension.gperf" + {"video/mp4", "mp4"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 70 "auto/mime_type_to_extension.gperf" + {"application/oda", "oda"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 111 "auto/mime_type_to_extension.gperf" + {"application/sdp", "sdp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 66 "auto/mime_type_to_extension.gperf" + {"application/mp4", "mp4s"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 615 "auto/mime_type_to_extension.gperf" + {"audio/vnd.dra", "dra"}, + {"",nullptr}, {"",nullptr}, +#line 74 "auto/mime_type_to_extension.gperf" + {"application/onenote", "onetoc"}, +#line 623 "auto/mime_type_to_extension.gperf" + {"audio/vnd.rip", "rip"}, +#line 644 "auto/mime_type_to_extension.gperf" + {"image/cgm", "cgm"}, + {"",nullptr}, {"",nullptr}, +#line 616 "auto/mime_type_to_extension.gperf" + {"audio/vnd.dts", "dts"}, + {"",nullptr}, {"",nullptr}, +#line 696 "auto/mime_type_to_extension.gperf" + {"model/vnd.mts", "mts"}, +#line 605 "auto/mime_type_to_extension.gperf" + {"audio/adpcm", "adp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 742 "auto/mime_type_to_extension.gperf" + {"video/3gpp", "3gp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 703 "auto/mime_type_to_extension.gperf" + {"text/calendar", "ics"}, + {"",nullptr}, {"",nullptr}, +#line 663 "auto/mime_type_to_extension.gperf" + {"image/vnd.fst", "fst"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 760 "auto/mime_type_to_extension.gperf" + {"video/vnd.fvt", "fvt"}, +#line 764 "auto/mime_type_to_extension.gperf" + {"video/vnd.vivo", "viv"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 707 "auto/mime_type_to_extension.gperf" + {"text/n3", "n3"}, + {"",nullptr}, {"",nullptr}, +#line 748 "auto/mime_type_to_extension.gperf" + {"video/jpm", "jpm"}, + {"",nullptr}, +#line 186 "auto/mime_type_to_extension.gperf" + {"application/vnd.dna", "dna"}, +#line 411 "auto/mime_type_to_extension.gperf" + {"application/vnd.sema", "sema"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 388 "auto/mime_type_to_extension.gperf" + {"application/vnd.palm", "pdb"}, + {"",nullptr}, {"",nullptr}, +#line 195 "auto/mime_type_to_extension.gperf" + {"application/vnd.enliven", "nml"}, + {"",nullptr}, +#line 261 "auto/mime_type_to_extension.gperf" + {"application/vnd.intergeo", "i2g"}, +#line 324 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-ims", "ims"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 386 "auto/mime_type_to_extension.gperf" + {"application/vnd.osgi.dp", "dp"}, +#line 460 "auto/mime_type_to_extension.gperf" + {"application/vnd.visio", "vsd"}, +#line 389 "auto/mime_type_to_extension.gperf" + {"application/vnd.pawaafile", "paw"}, +#line 716 "auto/mime_type_to_extension.gperf" + {"text/vcard", "vcard"}, +#line 443 "auto/mime_type_to_extension.gperf" + {"application/vnd.svd", "svd"}, +#line 184 "auto/mime_type_to_extension.gperf" + {"application/vnd.dece.zip", "uvz"}, +#line 412 "auto/mime_type_to_extension.gperf" + {"application/vnd.semd", "semd"}, +#line 49 "auto/mime_type_to_extension.gperf" + {"application/json", "json"}, + {"",nullptr}, {"",nullptr}, +#line 181 "auto/mime_type_to_extension.gperf" + {"application/vnd.dece.data", "uvf"}, + {"",nullptr}, {"",nullptr}, +#line 125 "auto/mime_type_to_extension.gperf" + {"application/timestamped-data", "tsd"}, + {"",nullptr}, +#line 65 "auto/mime_type_to_extension.gperf" + {"application/mp21", "m21"}, + {"",nullptr}, +#line 179 "auto/mime_type_to_extension.gperf" + {"application/vnd.dart", "dart"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 753 "auto/mime_type_to_extension.gperf" + {"video/quicktime", "mov"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 726 "auto/mime_type_to_extension.gperf" + {"text/vnd.in3d.spot", "spot"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 257 "auto/mime_type_to_extension.gperf" + {"application/vnd.immervision-ivp", "ivp"}, + {"",nullptr}, {"",nullptr}, +#line 326 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-officetheme", "thmx"}, + {"",nullptr}, +#line 329 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-powerpoint", "ppt"}, +#line 91 "auto/mime_type_to_extension.gperf" + {"application/postscript", "ai"}, + {"",nullptr}, {"",nullptr}, +#line 604 "auto/mime_type_to_extension.gperf" + {"application/zip", "zip"}, +#line 453 "auto/mime_type_to_extension.gperf" + {"application/vnd.trueapp", "tra"}, + {"",nullptr}, +#line 364 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.image", "odi"}, + {"",nullptr}, +#line 183 "auto/mime_type_to_extension.gperf" + {"application/vnd.dece.unspecified", "uvx"}, + {"",nullptr}, {"",nullptr}, +#line 743 "auto/mime_type_to_extension.gperf" + {"video/3gpp2", "3g2"}, +#line 306 "auto/mime_type_to_extension.gperf" + {"application/vnd.mobius.dis", "dis"}, +#line 730 "auto/mime_type_to_extension.gperf" + {"text/x-asm", "asm"}, +#line 366 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.presentation", "odp"}, +#line 365 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.image-template", "oti"}, + {"",nullptr}, {"",nullptr}, +#line 399 "auto/mime_type_to_extension.gperf" + {"application/vnd.pvi.ptid1", "ptid"}, +#line 359 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.database", "odb"}, + {"",nullptr}, +#line 297 "auto/mime_type_to_extension.gperf" + {"application/vnd.mcd", "mcd"}, + {"",nullptr}, +#line 367 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.presentation-template", "otp"}, +#line 369 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.spreadsheet-template", "ots"}, + {"",nullptr}, +#line 372 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.text-template", "ott"}, +#line 451 "auto/mime_type_to_extension.gperf" + {"application/vnd.trid.tpt", "tpt"}, +#line 368 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.spreadsheet", "ods"}, +#line 341 "auto/mime_type_to_extension.gperf" + {"application/vnd.mseq", "mseq"}, +#line 370 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.text", "odt"}, +#line 430 "auto/mime_type_to_extension.gperf" + {"application/vnd.stepmania.package", "smzip"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 191 "auto/mime_type_to_extension.gperf" + {"application/vnd.dvb.ait", "ait"}, + {"",nullptr}, +#line 405 "auto/mime_type_to_extension.gperf" + {"application/vnd.rim.cod", "cod"}, +#line 353 "auto/mime_type_to_extension.gperf" + {"application/vnd.nokia.radio-presets", "rpss"}, +#line 397 "auto/mime_type_to_extension.gperf" + {"application/vnd.proteus.magazine", "mgz"}, +#line 393 "auto/mime_type_to_extension.gperf" + {"application/vnd.pmi.widget", "wg"}, +#line 268 "auto/mime_type_to_extension.gperf" + {"application/vnd.jam", "jam"}, +#line 55 "auto/mime_type_to_extension.gperf" + {"application/marc", "mrc"}, + {"",nullptr}, +#line 749 "auto/mime_type_to_extension.gperf" + {"video/mj2", "mj2"}, + {"",nullptr}, +#line 352 "auto/mime_type_to_extension.gperf" + {"application/vnd.nokia.radio-preset", "rpst"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 270 "auto/mime_type_to_extension.gperf" + {"application/vnd.jisp", "jisp"}, +#line 737 "auto/mime_type_to_extension.gperf" + {"text/x-setext", "etx"}, + {"",nullptr}, +#line 33 "auto/mime_type_to_extension.gperf" + {"application/ecmascript", "ecma"}, +#line 732 "auto/mime_type_to_extension.gperf" + {"text/x-fortran", "f"}, + {"",nullptr}, +#line 371 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.text-master", "odm"}, +#line 731 "auto/mime_type_to_extension.gperf" + {"text/x-c", "c"}, +#line 452 "auto/mime_type_to_extension.gperf" + {"application/vnd.triscape.mxs", "mxs"}, +#line 423 "auto/mime_type_to_extension.gperf" + {"application/vnd.spotfire.sfs", "sfs"}, +#line 636 "auto/mime_type_to_extension.gperf" + {"audio/xm", "xm"}, + {"",nullptr}, {"",nullptr}, +#line 756 "auto/mime_type_to_extension.gperf" + {"video/vnd.dece.pd", "uvp"}, +#line 422 "auto/mime_type_to_extension.gperf" + {"application/vnd.spotfire.dxp", "dxp"}, +#line 757 "auto/mime_type_to_extension.gperf" + {"video/vnd.dece.sd", "uvs"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 618 "auto/mime_type_to_extension.gperf" + {"audio/vnd.lucent.voice", "lvp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 426 "auto/mime_type_to_extension.gperf" + {"application/vnd.stardivision.impress", "sdd"}, +#line 130 "auto/mime_type_to_extension.gperf" + {"application/vnd.3m.post-it-notes", "pwn"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 153 "auto/mime_type_to_extension.gperf" + {"application/vnd.astraea-software.iota", "iota"}, +#line 358 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.chart-template", "otc"}, + {"",nullptr}, +#line 741 "auto/mime_type_to_extension.gperf" + {"text/x-vcard", "vcf"}, +#line 758 "auto/mime_type_to_extension.gperf" + {"video/vnd.dece.video", "uvv"}, +#line 357 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.chart", "odc"}, +#line 131 "auto/mime_type_to_extension.gperf" + {"application/vnd.accpac.simply.aso", "aso"}, + {"",nullptr}, +#line 132 "auto/mime_type_to_extension.gperf" + {"application/vnd.accpac.simply.imp", "imp"}, +#line 679 "auto/mime_type_to_extension.gperf" + {"image/x-pict", "pic"}, +#line 327 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-pki.seccat", "cat"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 48 "auto/mime_type_to_extension.gperf" + {"application/javascript", "js"}, +#line 134 "auto/mime_type_to_extension.gperf" + {"application/vnd.acucorp", "atc"}, +#line 198 "auto/mime_type_to_extension.gperf" + {"application/vnd.epson.quickanime", "qam"}, +#line 632 "auto/mime_type_to_extension.gperf" + {"audio/x-ms-wma", "wma"}, + {"",nullptr}, +#line 36 "auto/mime_type_to_extension.gperf" + {"application/exi", "exi"}, +#line 666 "auto/mime_type_to_extension.gperf" + {"image/vnd.ms-modi", "mdi"}, +#line 267 "auto/mime_type_to_extension.gperf" + {"application/vnd.isac.fcs", "fcs"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 774 "auto/mime_type_to_extension.gperf" + {"video/x-ms-wm", "wm"}, + {"",nullptr}, +#line 780 "auto/mime_type_to_extension.gperf" + {"video/x-smv", "smv"}, +#line 431 "auto/mime_type_to_extension.gperf" + {"application/vnd.stepmania.stepchart", "sm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 75 "auto/mime_type_to_extension.gperf" + {"application/oxps", "oxps"}, +#line 166 "auto/mime_type_to_extension.gperf" + {"application/vnd.commonspace", "csp"}, +#line 769 "auto/mime_type_to_extension.gperf" + {"video/x-m4v", "m4v"}, + {"",nullptr}, +#line 428 "auto/mime_type_to_extension.gperf" + {"application/vnd.stardivision.writer", "sdw"}, + {"",nullptr}, {"",nullptr}, +#line 424 "auto/mime_type_to_extension.gperf" + {"application/vnd.stardivision.calc", "sdc"}, + {"",nullptr}, +#line 298 "auto/mime_type_to_extension.gperf" + {"application/vnd.medcalcdata", "mc1"}, +#line 420 "auto/mime_type_to_extension.gperf" + {"application/vnd.smart.teacher", "teacher"}, +#line 192 "auto/mime_type_to_extension.gperf" + {"application/vnd.dvb.service", "svc"}, +#line 331 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-powerpoint.presentation.macroenabled.12", "pptm"}, + {"",nullptr}, {"",nullptr}, +#line 333 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-powerpoint.slideshow.macroenabled.12", "ppsm"}, +#line 778 "auto/mime_type_to_extension.gperf" + {"video/x-msvideo", "avi"}, + {"",nullptr}, {"",nullptr}, +#line 334 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-powerpoint.template.macroenabled.12", "potm"}, + {"",nullptr}, +#line 112 "auto/mime_type_to_extension.gperf" + {"application/set-payment-initiation", "setpay"}, + {"",nullptr}, {"",nullptr}, +#line 449 "auto/mime_type_to_extension.gperf" + {"application/vnd.tcpdump.pcap", "pcap"}, +#line 625 "auto/mime_type_to_extension.gperf" + {"audio/x-aac", "aac"}, + {"",nullptr}, {"",nullptr}, +#line 676 "auto/mime_type_to_extension.gperf" + {"image/x-icon", "ico"}, +#line 672 "auto/mime_type_to_extension.gperf" + {"image/x-3ds", "3ds"}, +#line 330 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-powerpoint.addin.macroenabled.12", "ppam"}, + {"",nullptr}, +#line 775 "auto/mime_type_to_extension.gperf" + {"video/x-ms-wmv", "wmv"}, + {"",nullptr}, +#line 332 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-powerpoint.slide.macroenabled.12", "sldm"}, + {"",nullptr}, +#line 321 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-excel.template.macroenabled.12", "xltm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 25 "auto/mime_type_to_extension.gperf" + {"application/cdmi-domain", "cdmid"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 318 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-excel.addin.macroenabled.12", "xlam"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 320 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-excel.sheet.macroenabled.12", "xlsm"}, + {"",nullptr}, {"",nullptr}, +#line 69 "auto/mime_type_to_extension.gperf" + {"application/octet-stream", "bin"}, + {"",nullptr}, +#line 27 "auto/mime_type_to_extension.gperf" + {"application/cdmi-queue", "cdmiq"}, +#line 335 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-project", "mpp"}, + {"",nullptr}, {"",nullptr}, +#line 47 "auto/mime_type_to_extension.gperf" + {"application/java-vm", "class"}, + {"",nullptr}, {"",nullptr}, +#line 740 "auto/mime_type_to_extension.gperf" + {"text/x-vcalendar", "vcs"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 471 "auto/mime_type_to_extension.gperf" + {"application/vnd.xara", "xar"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 708 "auto/mime_type_to_extension.gperf" + {"text/plain", "txt"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 319 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-excel.sheet.binary.macroenabled.12", "xlsb"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 113 "auto/mime_type_to_extension.gperf" + {"application/set-registration-initiation", "setreg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 266 "auto/mime_type_to_extension.gperf" + {"application/vnd.is-xpr", "xpr"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 316 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-cab-compressed", "cab"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 45 "auto/mime_type_to_extension.gperf" + {"application/java-archive", "jar"}, +#line 459 "auto/mime_type_to_extension.gperf" + {"application/vnd.vcx", "vcx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 53 "auto/mime_type_to_extension.gperf" + {"application/mac-compactpro", "cpt"}, + {"",nullptr}, +#line 26 "auto/mime_type_to_extension.gperf" + {"application/cdmi-object", "cdmio"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 180 "auto/mime_type_to_extension.gperf" + {"application/vnd.data-vision.rdz", "rdz"}, + {"",nullptr}, {"",nullptr}, +#line 539 "auto/mime_type_to_extension.gperf" + {"application/x-mie", "mie"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 517 "auto/mime_type_to_extension.gperf" + {"application/x-eva", "eva"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 24 "auto/mime_type_to_extension.gperf" + {"application/cdmi-container", "cdmic"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 511 "auto/mime_type_to_extension.gperf" + {"application/x-doom", "wad"}, + {"",nullptr}, +#line 392 "auto/mime_type_to_extension.gperf" + {"application/vnd.picsel", "efif"}, +#line 515 "auto/mime_type_to_extension.gperf" + {"application/x-dvi", "dvi"}, + {"",nullptr}, +#line 325 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-lrm", "lrm"}, + {"",nullptr}, {"",nullptr}, +#line 673 "auto/mime_type_to_extension.gperf" + {"image/x-cmu-raster", "ras"}, + {"",nullptr}, {"",nullptr}, +#line 317 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-excel", "xls"}, + {"",nullptr}, +#line 576 "auto/mime_type_to_extension.gperf" + {"application/x-tads", "gam"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 169 "auto/mime_type_to_extension.gperf" + {"application/vnd.crick.clicker", "clkx"}, + {"",nullptr}, {"",nullptr}, +#line 172 "auto/mime_type_to_extension.gperf" + {"application/vnd.crick.clicker.template", "clkt"}, +#line 171 "auto/mime_type_to_extension.gperf" + {"application/vnd.crick.clicker.palette", "clkp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 550 "auto/mime_type_to_extension.gperf" + {"application/x-msdownload", "exe"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 304 "auto/mime_type_to_extension.gperf" + {"application/vnd.mif", "mif"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 727 "auto/mime_type_to_extension.gperf" + {"text/vnd.sun.j2me.app-descriptor", "jad"}, + {"",nullptr}, +#line 687 "auto/mime_type_to_extension.gperf" + {"image/x-xpixmap", "xpm"}, +#line 301 "auto/mime_type_to_extension.gperf" + {"application/vnd.mfmp", "mfm"}, +#line 110 "auto/mime_type_to_extension.gperf" + {"application/scvp-vp-response", "spp"}, +#line 577 "auto/mime_type_to_extension.gperf" + {"application/x-tar", "tar"}, +#line 199 "auto/mime_type_to_extension.gperf" + {"application/vnd.epson.salt", "slt"}, + {"",nullptr}, {"",nullptr}, +#line 462 "auto/mime_type_to_extension.gperf" + {"application/vnd.vsf", "vsf"}, +#line 506 "auto/mime_type_to_extension.gperf" + {"application/x-cpio", "cpio"}, +#line 735 "auto/mime_type_to_extension.gperf" + {"text/x-opml", "opml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 546 "auto/mime_type_to_extension.gperf" + {"application/x-msaccess", "mdb"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 662 "auto/mime_type_to_extension.gperf" + {"image/vnd.fpx", "fpx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 510 "auto/mime_type_to_extension.gperf" + {"application/x-director", "dir"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 678 "auto/mime_type_to_extension.gperf" + {"image/x-pcx", "pcx"}, +#line 674 "auto/mime_type_to_extension.gperf" + {"image/x-cmx", "cmx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 206 "auto/mime_type_to_extension.gperf" + {"application/vnd.fdsn.seed", "seed"}, +#line 573 "auto/mime_type_to_extension.gperf" + {"application/x-sv4cpio", "sv4cpio"}, + {"",nullptr}, {"",nullptr}, +#line 406 "auto/mime_type_to_extension.gperf" + {"application/vnd.rn-realmedia", "rm"}, + {"",nullptr}, +#line 109 "auto/mime_type_to_extension.gperf" + {"application/scvp-vp-request", "spq"}, +#line 118 "auto/mime_type_to_extension.gperf" + {"application/srgs", "gram"}, +#line 160 "auto/mime_type_to_extension.gperf" + {"application/vnd.cinderella", "cdy"}, +#line 734 "auto/mime_type_to_extension.gperf" + {"text/x-nfo", "nfo"}, +#line 108 "auto/mime_type_to_extension.gperf" + {"application/scvp-cv-response", "scs"}, +#line 360 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.formula", "odf"}, +#line 205 "auto/mime_type_to_extension.gperf" + {"application/vnd.fdsn.mseed", "mseed"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 300 "auto/mime_type_to_extension.gperf" + {"application/vnd.mfer", "mwf"}, + {"",nullptr}, {"",nullptr}, +#line 361 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.formula-template", "odft"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 715 "auto/mime_type_to_extension.gperf" + {"text/uri-list", "uri"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 260 "auto/mime_type_to_extension.gperf" + {"application/vnd.intercon.formnet", "xpw"}, + {"",nullptr}, {"",nullptr}, +#line 162 "auto/mime_type_to_extension.gperf" + {"application/vnd.cloanto.rp9", "rp9"}, +#line 168 "auto/mime_type_to_extension.gperf" + {"application/vnd.cosmocaller", "cmc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 738 "auto/mime_type_to_extension.gperf" + {"text/x-sfv", "sfv"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 620 "auto/mime_type_to_extension.gperf" + {"audio/vnd.nuera.ecelp4800", "ecelp4800"}, + {"",nullptr}, +#line 133 "auto/mime_type_to_extension.gperf" + {"application/vnd.acucobol", "acu"}, +#line 622 "auto/mime_type_to_extension.gperf" + {"audio/vnd.nuera.ecelp9600", "ecelp9600"}, +#line 227 "auto/mime_type_to_extension.gperf" + {"application/vnd.geoplan", "g2w"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 107 "auto/mime_type_to_extension.gperf" + {"application/scvp-cv-request", "scq"}, +#line 621 "auto/mime_type_to_extension.gperf" + {"audio/vnd.nuera.ecelp7470", "ecelp7470"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 50 "auto/mime_type_to_extension.gperf" + {"application/jsonml+json", "jsonml"}, +#line 145 "auto/mime_type_to_extension.gperf" + {"application/vnd.amiga.ami", "ami"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 391 "auto/mime_type_to_extension.gperf" + {"application/vnd.pg.osasli", "ei6"}, + {"",nullptr}, +#line 402 "auto/mime_type_to_extension.gperf" + {"application/vnd.recordare.musicxml", "mxl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 209 "auto/mime_type_to_extension.gperf" + {"application/vnd.framemaker", "fm"}, +#line 226 "auto/mime_type_to_extension.gperf" + {"application/vnd.geonext", "gxt"}, + {"",nullptr}, +#line 376 "auto/mime_type_to_extension.gperf" + {"application/vnd.openofficeorg.extension", "oxt"}, +#line 626 "auto/mime_type_to_extension.gperf" + {"audio/x-aiff", "aif"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 350 "auto/mime_type_to_extension.gperf" + {"application/vnd.nokia.n-gage.data", "ngdat"}, + {"",nullptr}, {"",nullptr}, +#line 256 "auto/mime_type_to_extension.gperf" + {"application/vnd.igloader", "igl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 664 "auto/mime_type_to_extension.gperf" + {"image/vnd.fujixerox.edmics-mmr", "mmr"}, + {"",nullptr}, {"",nullptr}, +#line 18 "auto/mime_type_to_extension.gperf" + {"application/applixware", "aw"}, + {"",nullptr}, {"",nullptr}, +#line 310 "auto/mime_type_to_extension.gperf" + {"application/vnd.mobius.plc", "plc"}, + {"",nullptr}, {"",nullptr}, +#line 354 "auto/mime_type_to_extension.gperf" + {"application/vnd.novadigm.edm", "edm"}, + {"",nullptr}, +#line 259 "auto/mime_type_to_extension.gperf" + {"application/vnd.insors.igm", "igm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 362 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.graphics", "odg"}, + {"",nullptr}, +#line 356 "auto/mime_type_to_extension.gperf" + {"application/vnd.novadigm.ext", "ext"}, + {"",nullptr}, +#line 590 "auto/mime_type_to_extension.gperf" + {"application/x-zmachine", "z1"}, +#line 363 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.graphics-template", "otg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 37 "auto/mime_type_to_extension.gperf" + {"application/font-tdpfr", "pfr"}, + {"",nullptr}, {"",nullptr}, +#line 80 "auto/mime_type_to_extension.gperf" + {"application/pics-rules", "prf"}, + {"",nullptr}, +#line 766 "auto/mime_type_to_extension.gperf" + {"video/x-f4v", "f4v"}, +#line 149 "auto/mime_type_to_extension.gperf" + {"application/vnd.antix.game-component", "atx"}, + {"",nullptr}, {"",nullptr}, +#line 228 "auto/mime_type_to_extension.gperf" + {"application/vnd.geospace", "g3w"}, + {"",nullptr}, {"",nullptr}, +#line 665 "auto/mime_type_to_extension.gperf" + {"image/vnd.fujixerox.edmics-rlc", "rlc"}, +#line 385 "auto/mime_type_to_extension.gperf" + {"application/vnd.osgeo.mapguide.package", "mgp"}, +#line 342 "auto/mime_type_to_extension.gperf" + {"application/vnd.musician", "mus"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 574 "auto/mime_type_to_extension.gperf" + {"application/x-sv4crc", "sv4crc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 129 "auto/mime_type_to_extension.gperf" + {"application/vnd.3gpp2.tcap", "tcap"}, + {"",nullptr}, {"",nullptr}, +#line 627 "auto/mime_type_to_extension.gperf" + {"audio/x-caf", "caf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 706 "auto/mime_type_to_extension.gperf" + {"text/html", "html"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 698 "auto/mime_type_to_extension.gperf" + {"model/vrml", "wrl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 455 "auto/mime_type_to_extension.gperf" + {"application/vnd.uiq.theme", "utz"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 348 "auto/mime_type_to_extension.gperf" + {"application/vnd.noblenet-sealer", "nns"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 269 "auto/mime_type_to_extension.gperf" + {"application/vnd.jcp.javame.midlet-rms", "rms"}, + {"",nullptr}, {"",nullptr}, +#line 541 "auto/mime_type_to_extension.gperf" + {"application/x-ms-application", "application"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 542 "auto/mime_type_to_extension.gperf" + {"application/x-ms-shortcut", "lnk"}, + {"",nullptr}, +#line 685 "auto/mime_type_to_extension.gperf" + {"image/x-tga", "tga"}, + {"",nullptr}, +#line 631 "auto/mime_type_to_extension.gperf" + {"audio/x-ms-wax", "wax"}, + {"",nullptr}, {"",nullptr}, +#line 689 "auto/mime_type_to_extension.gperf" + {"message/rfc822", "eml"}, +#line 771 "auto/mime_type_to_extension.gperf" + {"video/x-mng", "mng"}, + {"",nullptr}, +#line 763 "auto/mime_type_to_extension.gperf" + {"video/vnd.uvvu.mp4", "uvu"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 563 "auto/mime_type_to_extension.gperf" + {"application/x-rar-compressed", "rar"}, +#line 694 "auto/mime_type_to_extension.gperf" + {"model/vnd.gdl", "gdl"}, + {"",nullptr}, {"",nullptr}, +#line 776 "auto/mime_type_to_extension.gperf" + {"video/x-ms-wmx", "wmx"}, +#line 490 "auto/mime_type_to_extension.gperf" + {"application/x-ace-compressed", "ace"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 739 "auto/mime_type_to_extension.gperf" + {"text/x-uuencode", "uu"}, + {"",nullptr}, +#line 176 "auto/mime_type_to_extension.gperf" + {"application/vnd.cups-ppd", "ppd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 429 "auto/mime_type_to_extension.gperf" + {"application/vnd.stardivision.writer-global", "sgl"}, +#line 777 "auto/mime_type_to_extension.gperf" + {"video/x-ms-wvx", "wvx"}, + {"",nullptr}, +#line 456 "auto/mime_type_to_extension.gperf" + {"application/vnd.umajin", "umj"}, + {"",nullptr}, +#line 613 "auto/mime_type_to_extension.gperf" + {"audio/vnd.dece.audio", "uva"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 31 "auto/mime_type_to_extension.gperf" + {"application/dssc+der", "dssc"}, +#line 647 "auto/mime_type_to_extension.gperf" + {"image/ief", "ief"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 78 "auto/mime_type_to_extension.gperf" + {"application/pgp-encrypted", "pgp"}, + {"",nullptr}, {"",nullptr}, +#line 167 "auto/mime_type_to_extension.gperf" + {"application/vnd.contact.cmsg", "cdbcmsg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 378 "auto/mime_type_to_extension.gperf" + {"application/vnd.openxmlformats-officedocument.presentationml.slide", "sldx"}, + {"",nullptr}, +#line 382 "auto/mime_type_to_extension.gperf" + {"application/vnd.openxmlformats-officedocument.spreadsheetml.template", "xltx"}, +#line 380 "auto/mime_type_to_extension.gperf" + {"application/vnd.openxmlformats-officedocument.presentationml.template", "potx"}, + {"",nullptr}, +#line 384 "auto/mime_type_to_extension.gperf" + {"application/vnd.openxmlformats-officedocument.wordprocessingml.template", "dotx"}, + {"",nullptr}, +#line 377 "auto/mime_type_to_extension.gperf" + {"application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx"}, +#line 779 "auto/mime_type_to_extension.gperf" + {"video/x-sgi-movie", "movie"}, + {"",nullptr}, +#line 717 "auto/mime_type_to_extension.gperf" + {"text/vnd.curl", "curl"}, + {"",nullptr}, +#line 381 "auto/mime_type_to_extension.gperf" + {"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 383 "auto/mime_type_to_extension.gperf" + {"application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 410 "auto/mime_type_to_extension.gperf" + {"application/vnd.seemail", "see"}, +#line 552 "auto/mime_type_to_extension.gperf" + {"application/x-msmetafile", "wmf"}, +#line 448 "auto/mime_type_to_extension.gperf" + {"application/vnd.tao.intent-module-archive", "tao"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 77 "auto/mime_type_to_extension.gperf" + {"application/pdf", "pdf"}, + {"",nullptr}, +#line 596 "auto/mime_type_to_extension.gperf" + {"application/xml-dtd", "dtd"}, + {"",nullptr}, +#line 229 "auto/mime_type_to_extension.gperf" + {"application/vnd.gmx", "gmx"}, + {"",nullptr}, +#line 556 "auto/mime_type_to_extension.gperf" + {"application/x-msterminal", "trm"}, + {"",nullptr}, +#line 237 "auto/mime_type_to_extension.gperf" + {"application/vnd.groove-tool-message", "gtm"}, +#line 744 "auto/mime_type_to_extension.gperf" + {"video/h261", "h261"}, + {"",nullptr}, {"",nullptr}, +#line 651 "auto/mime_type_to_extension.gperf" + {"image/prs.btif", "btif"}, + {"",nullptr}, {"",nullptr}, +#line 238 "auto/mime_type_to_extension.gperf" + {"application/vnd.groove-tool-template", "tpl"}, + {"",nullptr}, +#line 302 "auto/mime_type_to_extension.gperf" + {"application/vnd.micrografx.flo", "flo"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 28 "auto/mime_type_to_extension.gperf" + {"application/cu-seeme", "cu"}, + {"",nullptr}, +#line 746 "auto/mime_type_to_extension.gperf" + {"video/h264", "h264"}, + {"",nullptr}, +#line 660 "auto/mime_type_to_extension.gperf" + {"image/vnd.dxf", "dxf"}, + {"",nullptr}, +#line 693 "auto/mime_type_to_extension.gperf" + {"model/vnd.dwf", "dwf"}, +#line 400 "auto/mime_type_to_extension.gperf" + {"application/vnd.quark.quarkxpress", "qxd"}, +#line 375 "auto/mime_type_to_extension.gperf" + {"application/vnd.oma.dd2+xml", "dd2"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 105 "auto/mime_type_to_extension.gperf" + {"application/rtf", "rtf"}, +#line 545 "auto/mime_type_to_extension.gperf" + {"application/x-ms-xbap", "xbap"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 309 "auto/mime_type_to_extension.gperf" + {"application/vnd.mobius.msl", "msl"}, + {"",nullptr}, +#line 488 "auto/mime_type_to_extension.gperf" + {"application/x-7z-compressed", "7z"}, +#line 637 "auto/mime_type_to_extension.gperf" + {"chemical/x-cdx", "cdx"}, + {"",nullptr}, {"",nullptr}, +#line 710 "auto/mime_type_to_extension.gperf" + {"text/richtext", "rtx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 736 "auto/mime_type_to_extension.gperf" + {"text/x-pascal", "pas"}, + {"",nullptr}, +#line 403 "auto/mime_type_to_extension.gperf" + {"application/vnd.recordare.musicxml+xml", "musicxml"}, +#line 328 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-pki.stl", "stl"}, + {"",nullptr}, {"",nullptr}, +#line 549 "auto/mime_type_to_extension.gperf" + {"application/x-msclip", "clp"}, +#line 534 "auto/mime_type_to_extension.gperf" + {"application/x-install-instructions", "install"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 725 "auto/mime_type_to_extension.gperf" + {"text/vnd.in3d.3dml", "3dml"}, +#line 712 "auto/mime_type_to_extension.gperf" + {"text/tab-separated-values", "tsv"}, + {"",nullptr}, +#line 525 "auto/mime_type_to_extension.gperf" + {"application/x-font-type1", "pfa"}, +#line 555 "auto/mime_type_to_extension.gperf" + {"application/x-msschedule", "scd"}, +#line 355 "auto/mime_type_to_extension.gperf" + {"application/vnd.novadigm.edx", "edx"}, + {"",nullptr}, +#line 225 "auto/mime_type_to_extension.gperf" + {"application/vnd.geometry-explorer", "gex"}, + {"",nullptr}, +#line 239 "auto/mime_type_to_extension.gperf" + {"application/vnd.groove-vcard", "vcg"}, +#line 150 "auto/mime_type_to_extension.gperf" + {"application/vnd.apple.installer+xml", "mpkg"}, +#line 548 "auto/mime_type_to_extension.gperf" + {"application/x-mscardfile", "crd"}, + {"",nullptr}, +#line 733 "auto/mime_type_to_extension.gperf" + {"text/x-java-source", "java"}, + {"",nullptr}, +#line 346 "auto/mime_type_to_extension.gperf" + {"application/vnd.nitf", "ntf"}, + {"",nullptr}, +#line 204 "auto/mime_type_to_extension.gperf" + {"application/vnd.fdf", "fdf"}, +#line 413 "auto/mime_type_to_extension.gperf" + {"application/vnd.semf", "semf"}, + {"",nullptr}, {"",nullptr}, +#line 419 "auto/mime_type_to_extension.gperf" + {"application/vnd.smaf", "mmf"}, + {"",nullptr}, +#line 57 "auto/mime_type_to_extension.gperf" + {"application/mathematica", "ma"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 585 "auto/mime_type_to_extension.gperf" + {"application/x-x509-ca-cert", "der"}, +#line 44 "auto/mime_type_to_extension.gperf" + {"application/ipfix", "ipfix"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 196 "auto/mime_type_to_extension.gperf" + {"application/vnd.epson.esf", "esf"}, + {"",nullptr}, {"",nullptr}, +#line 197 "auto/mime_type_to_extension.gperf" + {"application/vnd.epson.msf", "msf"}, +#line 200 "auto/mime_type_to_extension.gperf" + {"application/vnd.epson.ssf", "ssf"}, +#line 222 "auto/mime_type_to_extension.gperf" + {"application/vnd.genomatix.tuxedo", "txd"}, + {"",nullptr}, +#line 579 "auto/mime_type_to_extension.gperf" + {"application/x-tex", "tex"}, + {"",nullptr}, +#line 714 "auto/mime_type_to_extension.gperf" + {"text/turtle", "ttl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 745 "auto/mime_type_to_extension.gperf" + {"video/h263", "h263"}, + {"",nullptr}, +#line 589 "auto/mime_type_to_extension.gperf" + {"application/x-xz", "xz"}, + {"",nullptr}, +#line 617 "auto/mime_type_to_extension.gperf" + {"audio/vnd.dts.hd", "dtshd"}, + {"",nullptr}, {"",nullptr}, +#line 255 "auto/mime_type_to_extension.gperf" + {"application/vnd.iccprofile", "icc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 643 "auto/mime_type_to_extension.gperf" + {"image/bmp", "bmp"}, + {"",nullptr}, +#line 305 "auto/mime_type_to_extension.gperf" + {"application/vnd.mobius.daf", "daf"}, + {"",nullptr}, +#line 595 "auto/mime_type_to_extension.gperf" + {"application/xml", "xml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 610 "auto/mime_type_to_extension.gperf" + {"audio/ogg", "oga"}, + {"",nullptr}, +#line 650 "auto/mime_type_to_extension.gperf" + {"image/png", "png"}, + {"",nullptr}, {"",nullptr}, +#line 233 "auto/mime_type_to_extension.gperf" + {"application/vnd.groove-account", "gac"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 609 "auto/mime_type_to_extension.gperf" + {"audio/mpeg", "mp3"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 535 "auto/mime_type_to_extension.gperf" + {"application/x-iso9660-image", "iso"}, + {"",nullptr}, {"",nullptr}, +#line 752 "auto/mime_type_to_extension.gperf" + {"video/ogg", "ogv"}, +#line 677 "auto/mime_type_to_extension.gperf" + {"image/x-mrsid-image", "sid"}, + {"",nullptr}, +#line 526 "auto/mime_type_to_extension.gperf" + {"application/x-freearc", "arc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 236 "auto/mime_type_to_extension.gperf" + {"application/vnd.groove-injector", "grv"}, +#line 751 "auto/mime_type_to_extension.gperf" + {"video/mpeg", "mpeg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 767 "auto/mime_type_to_extension.gperf" + {"video/x-fli", "fli"}, + {"",nullptr}, +#line 491 "auto/mime_type_to_extension.gperf" + {"application/x-apple-diskimage", "dmg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 46 "auto/mime_type_to_extension.gperf" + {"application/java-serialized-object", "ser"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 532 "auto/mime_type_to_extension.gperf" + {"application/x-gtar", "gtar"}, +#line 312 "auto/mime_type_to_extension.gperf" + {"application/vnd.mophun.application", "mpn"}, + {"",nullptr}, {"",nullptr}, +#line 768 "auto/mime_type_to_extension.gperf" + {"video/x-flv", "flv"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 418 "auto/mime_type_to_extension.gperf" + {"application/vnd.simtech-mindmapper", "twd"}, +#line 146 "auto/mime_type_to_extension.gperf" + {"application/vnd.android.package-archive", "apk"}, + {"",nullptr}, +#line 29 "auto/mime_type_to_extension.gperf" + {"application/davmount+xml", "davmount"}, +#line 140 "auto/mime_type_to_extension.gperf" + {"application/vnd.ahead.space", "ahead"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 505 "auto/mime_type_to_extension.gperf" + {"application/x-conference", "nsc"}, +#line 427 "auto/mime_type_to_extension.gperf" + {"application/vnd.stardivision.math", "smf"}, + {"",nullptr}, +#line 606 "auto/mime_type_to_extension.gperf" + {"audio/basic", "au"}, +#line 659 "auto/mime_type_to_extension.gperf" + {"image/vnd.dwg", "dwg"}, + {"",nullptr}, +#line 754 "auto/mime_type_to_extension.gperf" + {"video/vnd.dece.hd", "uvh"}, + {"",nullptr}, {"",nullptr}, +#line 340 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-xpsdocument", "xps"}, +#line 390 "auto/mime_type_to_extension.gperf" + {"application/vnd.pg.format", "str"}, +#line 575 "auto/mime_type_to_extension.gperf" + {"application/x-t3vm-image", "t3"}, + {"",nullptr}, {"",nullptr}, +#line 537 "auto/mime_type_to_extension.gperf" + {"application/x-latex", "latex"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 628 "auto/mime_type_to_extension.gperf" + {"audio/x-flac", "flac"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 73 "auto/mime_type_to_extension.gperf" + {"application/omdoc+xml", "omdoc"}, + {"",nullptr}, +#line 583 "auto/mime_type_to_extension.gperf" + {"application/x-ustar", "ustar"}, + {"",nullptr}, +#line 68 "auto/mime_type_to_extension.gperf" + {"application/mxf", "mxf"}, +#line 247 "auto/mime_type_to_extension.gperf" + {"application/vnd.hp-jlyt", "jlt"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 292 "auto/mime_type_to_extension.gperf" + {"application/vnd.lotus-notes", "nsf"}, +#line 395 "auto/mime_type_to_extension.gperf" + {"application/vnd.powerbuilder6", "pbd"}, +#line 232 "auto/mime_type_to_extension.gperf" + {"application/vnd.grafeq", "gqf"}, +#line 175 "auto/mime_type_to_extension.gperf" + {"application/vnd.ctc-posml", "pml"}, + {"",nullptr}, {"",nullptr}, +#line 156 "auto/mime_type_to_extension.gperf" + {"application/vnd.bmi", "bmi"}, + {"",nullptr}, {"",nullptr}, +#line 648 "auto/mime_type_to_extension.gperf" + {"image/jpeg", "jpg"}, +#line 772 "auto/mime_type_to_extension.gperf" + {"video/x-ms-asf", "asf"}, + {"",nullptr}, +#line 640 "auto/mime_type_to_extension.gperf" + {"chemical/x-cml", "cml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 97 "auto/mime_type_to_extension.gperf" + {"application/resource-lists+xml", "rl"}, + {"",nullptr}, +#line 303 "auto/mime_type_to_extension.gperf" + {"application/vnd.micrografx.igx", "igx"}, + {"",nullptr}, {"",nullptr}, +#line 641 "auto/mime_type_to_extension.gperf" + {"chemical/x-csml", "csml"}, +#line 747 "auto/mime_type_to_extension.gperf" + {"video/jpeg", "jpgv"}, +#line 667 "auto/mime_type_to_extension.gperf" + {"image/vnd.ms-photo", "wdp"}, + {"",nullptr}, +#line 60 "auto/mime_type_to_extension.gperf" + {"application/mediaservercontrol+xml", "mscml"}, +#line 483 "auto/mime_type_to_extension.gperf" + {"application/voicexml+xml", "vxml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 313 "auto/mime_type_to_extension.gperf" + {"application/vnd.mophun.certificate", "mpc"}, +#line 536 "auto/mime_type_to_extension.gperf" + {"application/x-java-jnlp-file", "jnlp"}, + {"",nullptr}, +#line 436 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.impress", "sxi"}, +#line 294 "auto/mime_type_to_extension.gperf" + {"application/vnd.lotus-screencam", "scm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 286 "auto/mime_type_to_extension.gperf" + {"application/vnd.las.las+xml", "lasxml"}, +#line 581 "auto/mime_type_to_extension.gperf" + {"application/x-texinfo", "texinfo"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 187 "auto/mime_type_to_extension.gperf" + {"application/vnd.dolby.mlp", "mlp"}, + {"",nullptr}, +#line 437 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.impress.template", "sti"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 661 "auto/mime_type_to_extension.gperf" + {"image/vnd.fastbidsheet", "fbs"}, + {"",nullptr}, {"",nullptr}, +#line 645 "auto/mime_type_to_extension.gperf" + {"image/g3fax", "g3"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 564 "auto/mime_type_to_extension.gperf" + {"application/x-research-info-systems", "ris"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 177 "auto/mime_type_to_extension.gperf" + {"application/vnd.curl.car", "car"}, + {"",nullptr}, +#line 614 "auto/mime_type_to_extension.gperf" + {"audio/vnd.digital-winds", "eol"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 668 "auto/mime_type_to_extension.gperf" + {"image/vnd.net-fpx", "npx"}, +#line 252 "auto/mime_type_to_extension.gperf" + {"application/vnd.ibm.modcap", "afp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 163 "auto/mime_type_to_extension.gperf" + {"application/vnd.clonk.c4group", "c4g"}, + {"",nullptr}, +#line 373 "auto/mime_type_to_extension.gperf" + {"application/vnd.oasis.opendocument.text-web", "oth"}, +#line 481 "auto/mime_type_to_extension.gperf" + {"application/vnd.zul", "zir"}, + {"",nullptr}, {"",nullptr}, +#line 67 "auto/mime_type_to_extension.gperf" + {"application/msword", "doc"}, + {"",nullptr}, {"",nullptr}, +#line 435 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.draw.template", "std"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 502 "auto/mime_type_to_extension.gperf" + {"application/x-cfs-compressed", "cfs"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 234 "auto/mime_type_to_extension.gperf" + {"application/vnd.groove-help", "ghf"}, + {"",nullptr}, +#line 17 "auto/mime_type_to_extension.gperf" + {"application/andrew-inset", "ez"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 638 "auto/mime_type_to_extension.gperf" + {"chemical/x-cif", "cif"}, + {"",nullptr}, {"",nullptr}, +#line 569 "auto/mime_type_to_extension.gperf" + {"application/x-sql", "sql"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 271 "auto/mime_type_to_extension.gperf" + {"application/vnd.joost.joda-archive", "joda"}, +#line 374 "auto/mime_type_to_extension.gperf" + {"application/vnd.olpc-sugar", "xo"}, + {"",nullptr}, +#line 433 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.calc.template", "stc"}, + {"",nullptr}, +#line 711 "auto/mime_type_to_extension.gperf" + {"text/sgml", "sgml"}, + {"",nullptr}, {"",nullptr}, +#line 697 "auto/mime_type_to_extension.gperf" + {"model/vnd.vtu", "vtu"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 639 "auto/mime_type_to_extension.gperf" + {"chemical/x-cmdf", "cmdf"}, + {"",nullptr}, {"",nullptr}, +#line 469 "auto/mime_type_to_extension.gperf" + {"application/vnd.wqd", "wqd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 654 "auto/mime_type_to_extension.gperf" + {"image/tiff", "tiff"}, +#line 311 "auto/mime_type_to_extension.gperf" + {"application/vnd.mobius.txf", "txf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 657 "auto/mime_type_to_extension.gperf" + {"image/vnd.djvu", "djvu"}, + {"",nullptr}, +#line 265 "auto/mime_type_to_extension.gperf" + {"application/vnd.irepository.package+xml", "irp"}, + {"",nullptr}, {"",nullptr}, +#line 578 "auto/mime_type_to_extension.gperf" + {"application/x-tcl", "tcl"}, +#line 123 "auto/mime_type_to_extension.gperf" + {"application/tei+xml", "tei"}, +#line 432 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.calc", "sxc"}, + {"",nullptr}, +#line 633 "auto/mime_type_to_extension.gperf" + {"audio/x-pn-realaudio", "ram"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 208 "auto/mime_type_to_extension.gperf" + {"application/vnd.fluxtime.clip", "ftc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 713 "auto/mime_type_to_extension.gperf" + {"text/troff", "t"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 104 "auto/mime_type_to_extension.gperf" + {"application/rss+xml", "rss"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 103 "auto/mime_type_to_extension.gperf" + {"application/rsd+xml", "rsd"}, +#line 528 "auto/mime_type_to_extension.gperf" + {"application/x-gca-compressed", "gca"}, + {"",nullptr}, {"",nullptr}, +#line 442 "auto/mime_type_to_extension.gperf" + {"application/vnd.sus-calendar", "sus"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 670 "auto/mime_type_to_extension.gperf" + {"image/vnd.xiff", "xif"}, + {"",nullptr}, {"",nullptr}, +#line 509 "auto/mime_type_to_extension.gperf" + {"application/x-dgc-compressed", "dgc"}, + {"",nullptr}, {"",nullptr}, +#line 521 "auto/mime_type_to_extension.gperf" + {"application/x-font-otf", "otf"}, +#line 522 "auto/mime_type_to_extension.gperf" + {"application/x-font-pcf", "pcf"}, +#line 580 "auto/mime_type_to_extension.gperf" + {"application/x-tex-tfm", "tfm"}, +#line 523 "auto/mime_type_to_extension.gperf" + {"application/x-font-snf", "snf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 646 "auto/mime_type_to_extension.gperf" + {"image/gif", "gif"}, +#line 152 "auto/mime_type_to_extension.gperf" + {"application/vnd.aristanetworks.swi", "swi"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 524 "auto/mime_type_to_extension.gperf" + {"application/x-font-ttf", "ttf"}, + {"",nullptr}, +#line 248 "auto/mime_type_to_extension.gperf" + {"application/vnd.hp-pcl", "pcl"}, + {"",nullptr}, +#line 258 "auto/mime_type_to_extension.gperf" + {"application/vnd.immervision-ivu", "ivu"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 702 "auto/mime_type_to_extension.gperf" + {"text/cache-manifest", "appcache"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 79 "auto/mime_type_to_extension.gperf" + {"application/pgp-signature", "asc"}, + {"",nullptr}, {"",nullptr}, +#line 201 "auto/mime_type_to_extension.gperf" + {"application/vnd.eszigno3+xml", "es3"}, + {"",nullptr}, +#line 425 "auto/mime_type_to_extension.gperf" + {"application/vnd.stardivision.draw", "sda"}, + {"",nullptr}, +#line 635 "auto/mime_type_to_extension.gperf" + {"audio/x-wav", "wav"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 468 "auto/mime_type_to_extension.gperf" + {"application/vnd.wordperfect", "wpd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 598 "auto/mime_type_to_extension.gperf" + {"application/xproc+xml", "xpl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 263 "auto/mime_type_to_extension.gperf" + {"application/vnd.intu.qfx", "qfx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 151 "auto/mime_type_to_extension.gperf" + {"application/vnd.apple.mpegurl", "m3u8"}, +#line 566 "auto/mime_type_to_extension.gperf" + {"application/x-shar", "shar"}, +#line 558 "auto/mime_type_to_extension.gperf" + {"application/x-netcdf", "nc"}, +#line 254 "auto/mime_type_to_extension.gperf" + {"application/vnd.ibm.secure-container", "sc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 531 "auto/mime_type_to_extension.gperf" + {"application/x-gramps-xml", "gramps"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 135 "auto/mime_type_to_extension.gperf" + {"application/vnd.adobe.air-application-installer-package+zip", "air"}, + {"",nullptr}, {"",nullptr}, +#line 503 "auto/mime_type_to_extension.gperf" + {"application/x-chat", "chat"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 21 "auto/mime_type_to_extension.gperf" + {"application/atomsvc+xml", "atomsvc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 289 "auto/mime_type_to_extension.gperf" + {"application/vnd.lotus-1-2-3", "123"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 142 "auto/mime_type_to_extension.gperf" + {"application/vnd.airzip.filesecure.azs", "azs"}, + {"",nullptr}, +#line 458 "auto/mime_type_to_extension.gperf" + {"application/vnd.uoml+xml", "uoml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 207 "auto/mime_type_to_extension.gperf" + {"application/vnd.flographit", "gph"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 417 "auto/mime_type_to_extension.gperf" + {"application/vnd.shana.informed.package", "ipk"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 218 "auto/mime_type_to_extension.gperf" + {"application/vnd.fujixerox.ddd", "ddd"}, + {"",nullptr}, +#line 20 "auto/mime_type_to_extension.gperf" + {"application/atomcat+xml", "atomcat"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 336 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-word.document.macroenabled.12", "docm"}, +#line 588 "auto/mime_type_to_extension.gperf" + {"application/x-xpinstall", "xpi"}, +#line 414 "auto/mime_type_to_extension.gperf" + {"application/vnd.shana.informed.formdata", "ifm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 182 "auto/mime_type_to_extension.gperf" + {"application/vnd.dece.ttml+xml", "uvt"}, +#line 415 "auto/mime_type_to_extension.gperf" + {"application/vnd.shana.informed.formtemplate", "itp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 337 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-word.template.macroenabled.12", "dotm"}, + {"",nullptr}, +#line 284 "auto/mime_type_to_extension.gperf" + {"application/vnd.koan", "skp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 84 "auto/mime_type_to_extension.gperf" + {"application/pkcs8", "p8"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 416 "auto/mime_type_to_extension.gperf" + {"application/vnd.shana.informed.interchange", "iif"}, +#line 472 "auto/mime_type_to_extension.gperf" + {"application/vnd.xfdl", "xfdl"}, + {"",nullptr}, {"",nullptr}, +#line 570 "auto/mime_type_to_extension.gperf" + {"application/x-stuffit", "sit"}, +#line 597 "auto/mime_type_to_extension.gperf" + {"application/xop+xml", "xop"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 81 "auto/mime_type_to_extension.gperf" + {"application/pkcs10", "p10"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 291 "auto/mime_type_to_extension.gperf" + {"application/vnd.lotus-freelance", "pre"}, + {"",nullptr}, {"",nullptr}, +#line 231 "auto/mime_type_to_extension.gperf" + {"application/vnd.google-earth.kmz", "kmz"}, +#line 408 "auto/mime_type_to_extension.gperf" + {"application/vnd.route66.link66+xml", "link66"}, + {"",nullptr}, +#line 281 "auto/mime_type_to_extension.gperf" + {"application/vnd.kenameaapp", "htke"}, + {"",nullptr}, +#line 283 "auto/mime_type_to_extension.gperf" + {"application/vnd.kinar", "kne"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 117 "auto/mime_type_to_extension.gperf" + {"application/sparql-results+xml", "srx"}, + {"",nullptr}, {"",nullptr}, +#line 547 "auto/mime_type_to_extension.gperf" + {"application/x-msbinder", "obd"}, +#line 519 "auto/mime_type_to_extension.gperf" + {"application/x-font-ghostscript", "gsf"}, + {"",nullptr}, +#line 686 "auto/mime_type_to_extension.gperf" + {"image/x-xbitmap", "xbm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 59 "auto/mime_type_to_extension.gperf" + {"application/mbox", "mbox"}, + {"",nullptr}, {"",nullptr}, +#line 709 "auto/mime_type_to_extension.gperf" + {"text/prs.lines.tag", "dsc"}, +#line 495 "auto/mime_type_to_extension.gperf" + {"application/x-bcpio", "bcpio"}, +#line 450 "auto/mime_type_to_extension.gperf" + {"application/vnd.tmobile-livetv", "tmo"}, +#line 190 "auto/mime_type_to_extension.gperf" + {"application/vnd.ds-keypoint", "kpxx"}, + {"",nullptr}, {"",nullptr}, +#line 72 "auto/mime_type_to_extension.gperf" + {"application/ogg", "ogx"}, + {"",nullptr}, +#line 98 "auto/mime_type_to_extension.gperf" + {"application/resource-lists-diff+xml", "rld"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 496 "auto/mime_type_to_extension.gperf" + {"application/x-bittorrent", "torrent"}, + {"",nullptr}, +#line 276 "auto/mime_type_to_extension.gperf" + {"application/vnd.kde.kivio", "flw"}, +#line 137 "auto/mime_type_to_extension.gperf" + {"application/vnd.adobe.fxp", "fxp"}, + {"",nullptr}, +#line 279 "auto/mime_type_to_extension.gperf" + {"application/vnd.kde.kspread", "ksp"}, +#line 280 "auto/mime_type_to_extension.gperf" + {"application/vnd.kde.kword", "kwd"}, +#line 282 "auto/mime_type_to_extension.gperf" + {"application/vnd.kidspiration", "kia"}, + {"",nullptr}, +#line 504 "auto/mime_type_to_extension.gperf" + {"application/x-chess-pgn", "pgn"}, +#line 339 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-wpl", "wpl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 701 "auto/mime_type_to_extension.gperf" + {"model/x3d+xml", "x3d"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 210 "auto/mime_type_to_extension.gperf" + {"application/vnd.frogans.fnc", "fnc"}, + {"",nullptr}, +#line 273 "auto/mime_type_to_extension.gperf" + {"application/vnd.kde.karbon", "karbon"}, +#line 249 "auto/mime_type_to_extension.gperf" + {"application/vnd.hp-pclxl", "pclxl"}, + {"",nullptr}, {"",nullptr}, +#line 700 "auto/mime_type_to_extension.gperf" + {"model/x3d+vrml", "x3dv"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 224 "auto/mime_type_to_extension.gperf" + {"application/vnd.geogebra.tool", "ggt"}, +#line 675 "auto/mime_type_to_extension.gperf" + {"image/x-freehand", "fh"}, +#line 500 "auto/mime_type_to_extension.gperf" + {"application/x-cbr", "cbr"}, +#line 755 "auto/mime_type_to_extension.gperf" + {"video/vnd.dece.mobile", "uvm"}, +#line 723 "auto/mime_type_to_extension.gperf" + {"text/vnd.fmi.flexstor", "flx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 719 "auto/mime_type_to_extension.gperf" + {"text/vnd.curl.mcurl", "mcurl"}, +#line 720 "auto/mime_type_to_extension.gperf" + {"text/vnd.curl.scurl", "scurl"}, +#line 41 "auto/mime_type_to_extension.gperf" + {"application/gxf", "gxf"}, +#line 568 "auto/mime_type_to_extension.gperf" + {"application/x-silverlight-app", "xap"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 718 "auto/mime_type_to_extension.gperf" + {"text/vnd.curl.dcurl", "dcurl"}, +#line 557 "auto/mime_type_to_extension.gperf" + {"application/x-mswrite", "wri"}, + {"",nullptr}, +#line 498 "auto/mime_type_to_extension.gperf" + {"application/x-bzip", "bz"}, + {"",nullptr}, +#line 90 "auto/mime_type_to_extension.gperf" + {"application/pls+xml", "pls"}, +#line 630 "auto/mime_type_to_extension.gperf" + {"audio/x-mpegurl", "m3u"}, + {"",nullptr}, +#line 584 "auto/mime_type_to_extension.gperf" + {"application/x-wais-source", "src"}, + {"",nullptr}, +#line 34 "auto/mime_type_to_extension.gperf" + {"application/emma+xml", "emma"}, +#line 401 "auto/mime_type_to_extension.gperf" + {"application/vnd.realvnc.bed", "bed"}, + {"",nullptr}, +#line 264 "auto/mime_type_to_extension.gperf" + {"application/vnd.ipunplugged.rcprofile", "rcprofile"}, +#line 278 "auto/mime_type_to_extension.gperf" + {"application/vnd.kde.kpresenter", "kpr"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 407 "auto/mime_type_to_extension.gperf" + {"application/vnd.rn-realmedia-vbr", "rmvb"}, +#line 470 "auto/mime_type_to_extension.gperf" + {"application/vnd.wt.stf", "stf"}, +#line 223 "auto/mime_type_to_extension.gperf" + {"application/vnd.geogebra.file", "ggb"}, +#line 19 "auto/mime_type_to_extension.gperf" + {"application/atom+xml", "atom"}, +#line 54 "auto/mime_type_to_extension.gperf" + {"application/mads+xml", "mads"}, +#line 64 "auto/mime_type_to_extension.gperf" + {"application/mods+xml", "mods"}, +#line 63 "auto/mime_type_to_extension.gperf" + {"application/mets+xml", "mets"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 285 "auto/mime_type_to_extension.gperf" + {"application/vnd.kodak-descriptor", "sse"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 185 "auto/mime_type_to_extension.gperf" + {"application/vnd.denovo.fcselayout-link", "fe_launch"}, + {"",nullptr}, {"",nullptr}, +#line 629 "auto/mime_type_to_extension.gperf" + {"audio/x-matroska", "mka"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 102 "auto/mime_type_to_extension.gperf" + {"application/rpki-roa", "roa"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 464 "auto/mime_type_to_extension.gperf" + {"application/vnd.wap.wmlc", "wmlc"}, + {"",nullptr}, +#line 656 "auto/mime_type_to_extension.gperf" + {"image/vnd.dece.graphic", "uvi"}, +#line 530 "auto/mime_type_to_extension.gperf" + {"application/x-gnumeric", "gnumeric"}, +#line 293 "auto/mime_type_to_extension.gperf" + {"application/vnd.lotus-organizer", "org"}, +#line 770 "auto/mime_type_to_extension.gperf" + {"video/x-matroska", "mkv"}, +#line 82 "auto/mime_type_to_extension.gperf" + {"application/pkcs7-mime", "p7m"}, +#line 101 "auto/mime_type_to_extension.gperf" + {"application/rpki-manifest", "mft"}, + {"",nullptr}, +#line 484 "auto/mime_type_to_extension.gperf" + {"application/widget", "wgt"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 322 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-fontobject", "eot"}, + {"",nullptr}, {"",nullptr}, +#line 691 "auto/mime_type_to_extension.gperf" + {"model/mesh", "msh"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 94 "auto/mime_type_to_extension.gperf" + {"application/rdf+xml", "rdf"}, +#line 32 "auto/mime_type_to_extension.gperf" + {"application/dssc+xml", "xdssc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 193 "auto/mime_type_to_extension.gperf" + {"application/vnd.dynageo", "geo"}, + {"",nullptr}, {"",nullptr}, +#line 262 "auto/mime_type_to_extension.gperf" + {"application/vnd.intu.qbo", "qbo"}, +#line 314 "auto/mime_type_to_extension.gperf" + {"application/vnd.mozilla.xul+xml", "xul"}, + {"",nullptr}, +#line 499 "auto/mime_type_to_extension.gperf" + {"application/x-bzip2", "bz2"}, + {"",nullptr}, {"",nullptr}, +#line 323 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-htmlhelp", "chm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 213 "auto/mime_type_to_extension.gperf" + {"application/vnd.fujitsu.oasys", "oas"}, + {"",nullptr}, {"",nullptr}, +#line 203 "auto/mime_type_to_extension.gperf" + {"application/vnd.ezpix-package", "ez3"}, +#line 253 "auto/mime_type_to_extension.gperf" + {"application/vnd.ibm.rights-management", "irm"}, + {"",nullptr}, +#line 56 "auto/mime_type_to_extension.gperf" + {"application/marcxml+xml", "mrcx"}, +#line 571 "auto/mime_type_to_extension.gperf" + {"application/x-stuffitx", "sitx"}, + {"",nullptr}, +#line 216 "auto/mime_type_to_extension.gperf" + {"application/vnd.fujitsu.oasysgp", "fg5"}, +#line 724 "auto/mime_type_to_extension.gperf" + {"text/vnd.graphviz", "gv"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 174 "auto/mime_type_to_extension.gperf" + {"application/vnd.criticaltools.wbs+xml", "wbs"}, +#line 89 "auto/mime_type_to_extension.gperf" + {"application/pkixcmp", "pki"}, +#line 543 "auto/mime_type_to_extension.gperf" + {"application/x-ms-wmd", "wmd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 22 "auto/mime_type_to_extension.gperf" + {"application/ccxml+xml", "ccxml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 478 "auto/mime_type_to_extension.gperf" + {"application/vnd.yamaha.smaf-audio", "saf"}, +#line 299 "auto/mime_type_to_extension.gperf" + {"application/vnd.mediastation.cdkey", "cdkey"}, + {"",nullptr}, +#line 217 "auto/mime_type_to_extension.gperf" + {"application/vnd.fujitsu.oasysprs", "bh2"}, +#line 189 "auto/mime_type_to_extension.gperf" + {"application/vnd.dreamfactory", "dfac"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 272 "auto/mime_type_to_extension.gperf" + {"application/vnd.kahootz", "ktz"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 215 "auto/mime_type_to_extension.gperf" + {"application/vnd.fujitsu.oasys3", "oa3"}, + {"",nullptr}, {"",nullptr}, +#line 684 "auto/mime_type_to_extension.gperf" + {"image/x-rgb", "rgb"}, + {"",nullptr}, {"",nullptr}, +#line 479 "auto/mime_type_to_extension.gperf" + {"application/vnd.yamaha.smaf-phrase", "spf"}, +#line 404 "auto/mime_type_to_extension.gperf" + {"application/vnd.rig.cryptonote", "cryptonote"}, + {"",nullptr}, +#line 465 "auto/mime_type_to_extension.gperf" + {"application/vnd.wap.wmlscriptc", "wmlsc"}, + {"",nullptr}, +#line 692 "auto/mime_type_to_extension.gperf" + {"model/vnd.collada+xml", "dae"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 582 "auto/mime_type_to_extension.gperf" + {"application/x-tgif", "obj"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 246 "auto/mime_type_to_extension.gperf" + {"application/vnd.hp-hps", "hps"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 476 "auto/mime_type_to_extension.gperf" + {"application/vnd.yamaha.openscoreformat", "osf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 653 "auto/mime_type_to_extension.gperf" + {"image/svg+xml", "svg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 214 "auto/mime_type_to_extension.gperf" + {"application/vnd.fujitsu.oasys2", "oa2"}, +#line 454 "auto/mime_type_to_extension.gperf" + {"application/vnd.ufdl", "ufd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 245 "auto/mime_type_to_extension.gperf" + {"application/vnd.hp-hpid", "hpid"}, +#line 141 "auto/mime_type_to_extension.gperf" + {"application/vnd.airzip.filesecure.azf", "azf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 649 "auto/mime_type_to_extension.gperf" + {"image/ktx", "ktx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 188 "auto/mime_type_to_extension.gperf" + {"application/vnd.dpgraph", "dpg"}, + {"",nullptr}, +#line 345 "auto/mime_type_to_extension.gperf" + {"application/vnd.neurolanguage.nlu", "nlu"}, + {"",nullptr}, {"",nullptr}, +#line 99 "auto/mime_type_to_extension.gperf" + {"application/rls-services+xml", "rs"}, + {"",nullptr}, {"",nullptr}, +#line 120 "auto/mime_type_to_extension.gperf" + {"application/sru+xml", "sru"}, +#line 170 "auto/mime_type_to_extension.gperf" + {"application/vnd.crick.clicker.keyboard", "clkk"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 601 "auto/mime_type_to_extension.gperf" + {"application/xv+xml", "mxml"}, +#line 202 "auto/mime_type_to_extension.gperf" + {"application/vnd.ezpix-album", "ez2"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 211 "auto/mime_type_to_extension.gperf" + {"application/vnd.frogans.ltf", "ltf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 58 "auto/mime_type_to_extension.gperf" + {"application/mathml+xml", "mathml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 394 "auto/mime_type_to_extension.gperf" + {"application/vnd.pocketlearn", "plf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 379 "auto/mime_type_to_extension.gperf" + {"application/vnd.openxmlformats-officedocument.presentationml.slideshow", "ppsx"}, + {"",nullptr}, {"",nullptr}, +#line 759 "auto/mime_type_to_extension.gperf" + {"video/vnd.dvb.file", "dvb"}, + {"",nullptr}, +#line 126 "auto/mime_type_to_extension.gperf" + {"application/vnd.3gpp.pic-bw-large", "plb"}, + {"",nullptr}, {"",nullptr}, +#line 241 "auto/mime_type_to_extension.gperf" + {"application/vnd.handheld-entertainment+xml", "zmm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 475 "auto/mime_type_to_extension.gperf" + {"application/vnd.yamaha.hv-voice", "hvp"}, +#line 593 "auto/mime_type_to_extension.gperf" + {"application/xenc+xml", "xenc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 474 "auto/mime_type_to_extension.gperf" + {"application/vnd.yamaha.hv-script", "hvs"}, + {"",nullptr}, +#line 76 "auto/mime_type_to_extension.gperf" + {"application/patch-ops-error+xml", "xer"}, + {"",nullptr}, {"",nullptr}, +#line 128 "auto/mime_type_to_extension.gperf" + {"application/vnd.3gpp.pic-bw-var", "pvb"}, + {"",nullptr}, +#line 761 "auto/mime_type_to_extension.gperf" + {"video/vnd.mpegurl", "mxu"}, +#line 592 "auto/mime_type_to_extension.gperf" + {"application/xcap-diff+xml", "xdf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 242 "auto/mime_type_to_extension.gperf" + {"application/vnd.hbci", "hbci"}, +#line 86 "auto/mime_type_to_extension.gperf" + {"application/pkix-cert", "cer"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 438 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.math", "sxm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 290 "auto/mime_type_to_extension.gperf" + {"application/vnd.lotus-approach", "apr"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 115 "auto/mime_type_to_extension.gperf" + {"application/smil+xml", "smi"}, + {"",nullptr}, +#line 178 "auto/mime_type_to_extension.gperf" + {"application/vnd.curl.pcurl", "pcurl"}, +#line 122 "auto/mime_type_to_extension.gperf" + {"application/ssml+xml", "ssml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 51 "auto/mime_type_to_extension.gperf" + {"application/lost+xml", "lostxml"}, +#line 121 "auto/mime_type_to_extension.gperf" + {"application/ssdl+xml", "ssdl"}, + {"",nullptr}, {"",nullptr}, +#line 473 "auto/mime_type_to_extension.gperf" + {"application/vnd.yamaha.hv-dic", "hvd"}, + {"",nullptr}, +#line 23 "auto/mime_type_to_extension.gperf" + {"application/cdmi-capability", "cdmia"}, + {"",nullptr}, +#line 144 "auto/mime_type_to_extension.gperf" + {"application/vnd.americandynamics.acc", "acc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 398 "auto/mime_type_to_extension.gperf" + {"application/vnd.publishare-delta-tree", "qps"}, +#line 40 "auto/mime_type_to_extension.gperf" + {"application/gpx+xml", "gpx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 544 "auto/mime_type_to_extension.gperf" + {"application/x-ms-wmz", "wmz"}, +#line 85 "auto/mime_type_to_extension.gperf" + {"application/pkix-attr-cert", "ac"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 722 "auto/mime_type_to_extension.gperf" + {"text/vnd.fly", "fly"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 467 "auto/mime_type_to_extension.gperf" + {"application/vnd.wolfram.player", "nbp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 516 "auto/mime_type_to_extension.gperf" + {"application/x-envoy", "evy"}, + {"",nullptr}, +#line 553 "auto/mime_type_to_extension.gperf" + {"application/x-msmoney", "mny"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 136 "auto/mime_type_to_extension.gperf" + {"application/vnd.adobe.formscentral.fcdt", "fcdt"}, + {"",nullptr}, +#line 538 "auto/mime_type_to_extension.gperf" + {"application/x-lzh-compressed", "lzh"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 296 "auto/mime_type_to_extension.gperf" + {"application/vnd.macports.portpkg", "portpkg"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 671 "auto/mime_type_to_extension.gperf" + {"image/webp", "webp"}, +#line 624 "auto/mime_type_to_extension.gperf" + {"audio/webm", "weba"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 572 "auto/mime_type_to_extension.gperf" + {"application/x-subrip", "srt"}, +#line 164 "auto/mime_type_to_extension.gperf" + {"application/vnd.cluetrust.cartomobile-config", "c11amc"}, +#line 721 "auto/mime_type_to_extension.gperf" + {"text/vnd.dvb.subtitle", "sub"}, +#line 683 "auto/mime_type_to_extension.gperf" + {"image/x-portable-pixmap", "ppm"}, +#line 230 "auto/mime_type_to_extension.gperf" + {"application/vnd.google-earth.kml+xml", "kml"}, +#line 165 "auto/mime_type_to_extension.gperf" + {"application/vnd.cluetrust.cartomobile-config-pkg", "c11amz"}, + {"",nullptr}, +#line 765 "auto/mime_type_to_extension.gperf" + {"video/webm", "webm"}, + {"",nullptr}, {"",nullptr}, +#line 155 "auto/mime_type_to_extension.gperf" + {"application/vnd.blueice.multipass", "mpm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 39 "auto/mime_type_to_extension.gperf" + {"application/gml+xml", "gml"}, + {"",nullptr}, {"",nullptr}, +#line 512 "auto/mime_type_to_extension.gperf" + {"application/x-dtbncx+xml", "ncx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 560 "auto/mime_type_to_extension.gperf" + {"application/x-pkcs12", "p12"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 533 "auto/mime_type_to_extension.gperf" + {"application/x-hdf", "hdf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 586 "auto/mime_type_to_extension.gperf" + {"application/x-xfig", "fig"}, +#line 275 "auto/mime_type_to_extension.gperf" + {"application/vnd.kde.kformula", "kfo"}, + {"",nullptr}, +#line 565 "auto/mime_type_to_extension.gperf" + {"application/x-sh", "sh"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 221 "auto/mime_type_to_extension.gperf" + {"application/vnd.fuzzysheet", "fzs"}, + {"",nullptr}, +#line 116 "auto/mime_type_to_extension.gperf" + {"application/sparql-query", "rq"}, + {"",nullptr}, {"",nullptr}, +#line 124 "auto/mime_type_to_extension.gperf" + {"application/thraud+xml", "tfi"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 634 "auto/mime_type_to_extension.gperf" + {"audio/x-pn-realaudio-plugin", "rmp"}, +#line 119 "auto/mime_type_to_extension.gperf" + {"application/srgs+xml", "grxml"}, +#line 161 "auto/mime_type_to_extension.gperf" + {"application/vnd.claymore", "cla"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 277 "auto/mime_type_to_extension.gperf" + {"application/vnd.kde.kontour", "kon"}, +#line 52 "auto/mime_type_to_extension.gperf" + {"application/mac-binhex40", "hqx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 344 "auto/mime_type_to_extension.gperf" + {"application/vnd.mynfc", "taglet"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 477 "auto/mime_type_to_extension.gperf" + {"application/vnd.yamaha.openscoreformat.osfpvg+xml", "osfpvg"}, + {"",nullptr}, +#line 493 "auto/mime_type_to_extension.gperf" + {"application/x-authorware-map", "aam"}, +#line 61 "auto/mime_type_to_extension.gperf" + {"application/metalink+xml", "metalink"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 194 "auto/mime_type_to_extension.gperf" + {"application/vnd.ecowin.chart", "mag"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 562 "auto/mime_type_to_extension.gperf" + {"application/x-pkcs7-certreqresp", "p7r"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 71 "auto/mime_type_to_extension.gperf" + {"application/oebps-package+xml", "opf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 463 "auto/mime_type_to_extension.gperf" + {"application/vnd.wap.wbxml", "wbxml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 295 "auto/mime_type_to_extension.gperf" + {"application/vnd.lotus-wordpro", "lwp"}, +#line 507 "auto/mime_type_to_extension.gperf" + {"application/x-csh", "csh"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 466 "auto/mime_type_to_extension.gperf" + {"application/vnd.webturbo", "wtb"}, +#line 669 "auto/mime_type_to_extension.gperf" + {"image/vnd.wap.wbmp", "wbmp"}, +#line 591 "auto/mime_type_to_extension.gperf" + {"application/xaml+xml", "xaml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 695 "auto/mime_type_to_extension.gperf" + {"model/vnd.gtw", "gtw"}, + {"",nullptr}, {"",nullptr}, +#line 139 "auto/mime_type_to_extension.gperf" + {"application/vnd.adobe.xfdf", "xfdf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 599 "auto/mime_type_to_extension.gperf" + {"application/xslt+xml", "xslt"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 434 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.draw", "sxd"}, + {"",nullptr}, {"",nullptr}, +#line 127 "auto/mime_type_to_extension.gperf" + {"application/vnd.3gpp.pic-bw-small", "psb"}, +#line 642 "auto/mime_type_to_extension.gperf" + {"chemical/x-xyz", "xyz"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 158 "auto/mime_type_to_extension.gperf" + {"application/vnd.chemdraw+xml", "cdxml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 439 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.writer", "sxw"}, + {"",nullptr}, {"",nullptr}, +#line 240 "auto/mime_type_to_extension.gperf" + {"application/vnd.hal+xml", "hal"}, + {"",nullptr}, {"",nullptr}, +#line 347 "auto/mime_type_to_extension.gperf" + {"application/vnd.noblenet-directory", "nnd"}, + {"",nullptr}, +#line 600 "auto/mime_type_to_extension.gperf" + {"application/xspf+xml", "xspf"}, + {"",nullptr}, {"",nullptr}, +#line 457 "auto/mime_type_to_extension.gperf" + {"application/vnd.unity", "unityweb"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 421 "auto/mime_type_to_extension.gperf" + {"application/vnd.solent.sdkm+xml", "sdkm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 773 "auto/mime_type_to_extension.gperf" + {"video/x-ms-vob", "vob"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 518 "auto/mime_type_to_extension.gperf" + {"application/x-font-bdf", "bdf"}, + {"",nullptr}, +#line 387 "auto/mime_type_to_extension.gperf" + {"application/vnd.osgi.subsystem", "esa"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 83 "auto/mime_type_to_extension.gperf" + {"application/pkcs7-signature", "p7s"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 95 "auto/mime_type_to_extension.gperf" + {"application/reginfo+xml", "rif"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 485 "auto/mime_type_to_extension.gperf" + {"application/winhlp", "hlp"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 138 "auto/mime_type_to_extension.gperf" + {"application/vnd.adobe.xdp+xml", "xdp"}, + {"",nullptr}, +#line 682 "auto/mime_type_to_extension.gperf" + {"image/x-portable-graymap", "pgm"}, +#line 554 "auto/mime_type_to_extension.gperf" + {"application/x-mspublisher", "pub"}, +#line 92 "auto/mime_type_to_extension.gperf" + {"application/prs.cww", "cww"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 35 "auto/mime_type_to_extension.gperf" + {"application/epub+zip", "epub"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 482 "auto/mime_type_to_extension.gperf" + {"application/vnd.zzazz.deck+xml", "zaz"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 148 "auto/mime_type_to_extension.gperf" + {"application/vnd.anser-web-funds-transfer-initiation", "fti"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 147 "auto/mime_type_to_extension.gperf" + {"application/vnd.anser-web-certificate-issue-initiation", "cii"}, +#line 520 "auto/mime_type_to_extension.gperf" + {"application/x-font-linux-psf", "psf"}, + {"",nullptr}, {"",nullptr}, +#line 154 "auto/mime_type_to_extension.gperf" + {"application/vnd.audiograph", "aep"}, + {"",nullptr}, +#line 274 "auto/mime_type_to_extension.gperf" + {"application/vnd.kde.kchart", "chrt"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 235 "auto/mime_type_to_extension.gperf" + {"application/vnd.groove-identity-message", "gim"}, +#line 30 "auto/mime_type_to_extension.gperf" + {"application/docbook+xml", "dbk"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 594 "auto/mime_type_to_extension.gperf" + {"application/xhtml+xml", "xhtml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 114 "auto/mime_type_to_extension.gperf" + {"application/shf+xml", "shf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 529 "auto/mime_type_to_extension.gperf" + {"application/x-glulx", "ulx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 244 "auto/mime_type_to_extension.gperf" + {"application/vnd.hp-hpgl", "hpgl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 514 "auto/mime_type_to_extension.gperf" + {"application/x-dtbresource+xml", "res"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 219 "auto/mime_type_to_extension.gperf" + {"application/vnd.fujixerox.docuworks", "xdw"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 38 "auto/mime_type_to_extension.gperf" + {"application/font-woff", "woff"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 561 "auto/mime_type_to_extension.gperf" + {"application/x-pkcs7-certificates", "p7b"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 338 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-works", "wps"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 559 "auto/mime_type_to_extension.gperf" + {"application/x-nzb", "nzb"}, + {"",nullptr}, {"",nullptr}, +#line 489 "auto/mime_type_to_extension.gperf" + {"application/x-abiword", "abw"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 351 "auto/mime_type_to_extension.gperf" + {"application/vnd.nokia.n-gage.symbian.install", "n-gage"}, + {"",nullptr}, {"",nullptr}, +#line 602 "auto/mime_type_to_extension.gperf" + {"application/yang", "yang"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 315 "auto/mime_type_to_extension.gperf" + {"application/vnd.ms-artgalry", "cil"}, +#line 220 "auto/mime_type_to_extension.gperf" + {"application/vnd.fujixerox.docuworks.binder", "xbd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 87 "auto/mime_type_to_extension.gperf" + {"application/pkix-crl", "crl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 440 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.writer.global", "sxg"}, + {"",nullptr}, +#line 441 "auto/mime_type_to_extension.gperf" + {"application/vnd.sun.xml.writer.template", "stw"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 343 "auto/mime_type_to_extension.gperf" + {"application/vnd.muvee.style", "msty"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 551 "auto/mime_type_to_extension.gperf" + {"application/x-msmediaview", "mvb"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 494 "auto/mime_type_to_extension.gperf" + {"application/x-authorware-seg", "aas"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 143 "auto/mime_type_to_extension.gperf" + {"application/vnd.amazon.ebook", "azw"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 88 "auto/mime_type_to_extension.gperf" + {"application/pkix-pkipath", "pkipath"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 43 "auto/mime_type_to_extension.gperf" + {"application/inkml+xml", "ink"}, +#line 480 "auto/mime_type_to_extension.gperf" + {"application/vnd.yellowriver-custom-menu", "cmp"}, + {"",nullptr}, {"",nullptr}, +#line 251 "auto/mime_type_to_extension.gperf" + {"application/vnd.ibm.minipay", "mpy"}, + {"",nullptr}, {"",nullptr}, +#line 729 "auto/mime_type_to_extension.gperf" + {"text/vnd.wap.wmlscript", "wmls"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 157 "auto/mime_type_to_extension.gperf" + {"application/vnd.businessobjects", "rep"}, +#line 349 "auto/mime_type_to_extension.gperf" + {"application/vnd.noblenet-web", "nnw"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 658 "auto/mime_type_to_extension.gperf" + {"image/vnd.dvb.subtitle", "sub"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 447 "auto/mime_type_to_extension.gperf" + {"application/vnd.syncml.dm+xml", "xdm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 62 "auto/mime_type_to_extension.gperf" + {"application/metalink4+xml", "meta4"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 587 "auto/mime_type_to_extension.gperf" + {"application/x-xliff+xml", "xlf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 603 "auto/mime_type_to_extension.gperf" + {"application/yin+xml", "yin"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 497 "auto/mime_type_to_extension.gperf" + {"application/x-blorb", "blb"}, + {"",nullptr}, {"",nullptr}, +#line 681 "auto/mime_type_to_extension.gperf" + {"image/x-portable-bitmap", "pbm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 655 "auto/mime_type_to_extension.gperf" + {"image/vnd.adobe.photoshop", "psd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 508 "auto/mime_type_to_extension.gperf" + {"application/x-debian-package", "deb"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 173 "auto/mime_type_to_extension.gperf" + {"application/vnd.crick.clicker.wordbank", "clkw"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 106 "auto/mime_type_to_extension.gperf" + {"application/sbml+xml", "sbml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 728 "auto/mime_type_to_extension.gperf" + {"text/vnd.wap.wml", "wml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 212 "auto/mime_type_to_extension.gperf" + {"application/vnd.fsc.weblaunch", "fsc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 540 "auto/mime_type_to_extension.gperf" + {"application/x-mobipocket-ebook", "prc"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 250 "auto/mime_type_to_extension.gperf" + {"application/vnd.hydrostatix.sof-data", "sfd-hdstx"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 93 "auto/mime_type_to_extension.gperf" + {"application/pskc+xml", "pskcxml"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 486 "auto/mime_type_to_extension.gperf" + {"application/wsdl+xml", "wsdl"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 445 "auto/mime_type_to_extension.gperf" + {"application/vnd.syncml+xml", "xsm"}, +#line 612 "auto/mime_type_to_extension.gperf" + {"audio/silk", "sil"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 42 "auto/mime_type_to_extension.gperf" + {"application/hyperstudio", "stk"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 446 "auto/mime_type_to_extension.gperf" + {"application/vnd.syncml.dm+wbxml", "bdm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 396 "auto/mime_type_to_extension.gperf" + {"application/vnd.previewsystems.box", "box"}, + {"",nullptr}, {"",nullptr}, +#line 287 "auto/mime_type_to_extension.gperf" + {"application/vnd.llamagraphics.life-balance.desktop", "lbd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 492 "auto/mime_type_to_extension.gperf" + {"application/x-authorware-bin", "aab"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 100 "auto/mime_type_to_extension.gperf" + {"application/rpki-ghostbusters", "gbr"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 96 "auto/mime_type_to_extension.gperf" + {"application/relax-ng-compact-syntax", "rnc"}, + {"",nullptr}, +#line 513 "auto/mime_type_to_extension.gperf" + {"application/x-dtbook+xml", "dtb"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 461 "auto/mime_type_to_extension.gperf" + {"application/vnd.visionary", "vis"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 688 "auto/mime_type_to_extension.gperf" + {"image/x-xwindowdump", "xwd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 308 "auto/mime_type_to_extension.gperf" + {"application/vnd.mobius.mqy", "mqy"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 680 "auto/mime_type_to_extension.gperf" + {"image/x-portable-anymap", "pnm"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 444 "auto/mime_type_to_extension.gperf" + {"application/vnd.symbian.install", "sis"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 487 "auto/mime_type_to_extension.gperf" + {"application/wspolicy+xml", "wspolicy"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 243 "auto/mime_type_to_extension.gperf" + {"application/vnd.hhe.lesson-player", "les"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 288 "auto/mime_type_to_extension.gperf" + {"application/vnd.llamagraphics.life-balance.exchange+xml", "lbe"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 781 "auto/mime_type_to_extension.gperf" + {"x-conference/x-cooltalk", "ice"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 501 "auto/mime_type_to_extension.gperf" + {"application/x-cdlink", "vcd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, +#line 409 "auto/mime_type_to_extension.gperf" + {"application/vnd.sailingtracker.track", "st"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 159 "auto/mime_type_to_extension.gperf" + {"application/vnd.chipnuts.karaoke-mmd", "mmd"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 619 "auto/mime_type_to_extension.gperf" + {"audio/vnd.ms-playready.media.pya", "pya"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, +#line 307 "auto/mime_type_to_extension.gperf" + {"application/vnd.mobius.mbk", "mbk"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 762 "auto/mime_type_to_extension.gperf" + {"video/vnd.ms-playready.media.pyv", "pyv"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 699 "auto/mime_type_to_extension.gperf" + {"model/x3d+binary", "x3db"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 567 "auto/mime_type_to_extension.gperf" + {"application/x-shockwave-flash", "swf"}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, {"",nullptr}, + {"",nullptr}, {"",nullptr}, {"",nullptr}, +#line 527 "auto/mime_type_to_extension.gperf" + {"application/x-futuresplash", "spl"} + }; + + if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) + { + unsigned int key = mime_type_hash (str, len); + + if (key <= MAX_HASH_VALUE) + { + register const char *s = wordlist[key].mime_type; + + if ((((unsigned char)*str ^ (unsigned char)*s) & ~32) == 0 && !gperf_case_strcmp (str, s)) + return &wordlist[key]; + } + } + return 0; +} +#line 782 "auto/mime_type_to_extension.gperf" + +const char *mime_type_to_extension(const char *mime_type, size_t mime_type_len) { + const auto &result = search_mime_type(mime_type, mime_type_len); + if (result == nullptr) { + return nullptr; + } + + return result->extension; +} diff --git a/submodules/ton/tonlib-src/tdutils/generate/auto/mime_type_to_extension.gperf b/submodules/ton/tonlib-src/tdutils/generate/auto/mime_type_to_extension.gperf new file mode 100644 index 00000000000..f24d6b440f5 --- /dev/null +++ b/submodules/ton/tonlib-src/tdutils/generate/auto/mime_type_to_extension.gperf @@ -0,0 +1,790 @@ +%struct-type +%ignore-case +%language=ANSI-C +%readonly-tables +%includes +%enum +%define slot-name mime_type +%define initializer-suffix ,nullptr +%define slot-name mime_type +%define hash-function-name mime_type_hash +%define lookup-function-name search_mime_type +struct mime_type_and_extension { + const char *mime_type; + const char *extension; +} +%% +"application/andrew-inset", "ez" +"application/applixware", "aw" +"application/atom+xml", "atom" +"application/atomcat+xml", "atomcat" +"application/atomsvc+xml", "atomsvc" +"application/ccxml+xml", "ccxml" +"application/cdmi-capability", "cdmia" +"application/cdmi-container", "cdmic" +"application/cdmi-domain", "cdmid" +"application/cdmi-object", "cdmio" +"application/cdmi-queue", "cdmiq" +"application/cu-seeme", "cu" +"application/davmount+xml", "davmount" +"application/docbook+xml", "dbk" +"application/dssc+der", "dssc" +"application/dssc+xml", "xdssc" +"application/ecmascript", "ecma" +"application/emma+xml", "emma" +"application/epub+zip", "epub" +"application/exi", "exi" +"application/font-tdpfr", "pfr" +"application/font-woff", "woff" +"application/gml+xml", "gml" +"application/gpx+xml", "gpx" +"application/gxf", "gxf" +"application/hyperstudio", "stk" +"application/inkml+xml", "ink" +"application/ipfix", "ipfix" +"application/java-archive", "jar" +"application/java-serialized-object", "ser" +"application/java-vm", "class" +"application/javascript", "js" +"application/json", "json" +"application/jsonml+json", "jsonml" +"application/lost+xml", "lostxml" +"application/mac-binhex40", "hqx" +"application/mac-compactpro", "cpt" +"application/mads+xml", "mads" +"application/marc", "mrc" +"application/marcxml+xml", "mrcx" +"application/mathematica", "ma" +"application/mathml+xml", "mathml" +"application/mbox", "mbox" +"application/mediaservercontrol+xml", "mscml" +"application/metalink+xml", "metalink" +"application/metalink4+xml", "meta4" +"application/mets+xml", "mets" +"application/mods+xml", "mods" +"application/mp21", "m21" +"application/mp4", "mp4s" +"application/msword", "doc" +"application/mxf", "mxf" +"application/octet-stream", "bin" +"application/oda", "oda" +"application/oebps-package+xml", "opf" +"application/ogg", "ogx" +"application/omdoc+xml", "omdoc" +"application/onenote", "onetoc" +"application/oxps", "oxps" +"application/patch-ops-error+xml", "xer" +"application/pdf", "pdf" +"application/pgp-encrypted", "pgp" +"application/pgp-signature", "asc" +"application/pics-rules", "prf" +"application/pkcs10", "p10" +"application/pkcs7-mime", "p7m" +"application/pkcs7-signature", "p7s" +"application/pkcs8", "p8" +"application/pkix-attr-cert", "ac" +"application/pkix-cert", "cer" +"application/pkix-crl", "crl" +"application/pkix-pkipath", "pkipath" +"application/pkixcmp", "pki" +"application/pls+xml", "pls" +"application/postscript", "ai" +"application/prs.cww", "cww" +"application/pskc+xml", "pskcxml" +"application/rdf+xml", "rdf" +"application/reginfo+xml", "rif" +"application/relax-ng-compact-syntax", "rnc" +"application/resource-lists+xml", "rl" +"application/resource-lists-diff+xml", "rld" +"application/rls-services+xml", "rs" +"application/rpki-ghostbusters", "gbr" +"application/rpki-manifest", "mft" +"application/rpki-roa", "roa" +"application/rsd+xml", "rsd" +"application/rss+xml", "rss" +"application/rtf", "rtf" +"application/sbml+xml", "sbml" +"application/scvp-cv-request", "scq" +"application/scvp-cv-response", "scs" +"application/scvp-vp-request", "spq" +"application/scvp-vp-response", "spp" +"application/sdp", "sdp" +"application/set-payment-initiation", "setpay" +"application/set-registration-initiation", "setreg" +"application/shf+xml", "shf" +"application/smil+xml", "smi" +"application/sparql-query", "rq" +"application/sparql-results+xml", "srx" +"application/srgs", "gram" +"application/srgs+xml", "grxml" +"application/sru+xml", "sru" +"application/ssdl+xml", "ssdl" +"application/ssml+xml", "ssml" +"application/tei+xml", "tei" +"application/thraud+xml", "tfi" +"application/timestamped-data", "tsd" +"application/vnd.3gpp.pic-bw-large", "plb" +"application/vnd.3gpp.pic-bw-small", "psb" +"application/vnd.3gpp.pic-bw-var", "pvb" +"application/vnd.3gpp2.tcap", "tcap" +"application/vnd.3m.post-it-notes", "pwn" +"application/vnd.accpac.simply.aso", "aso" +"application/vnd.accpac.simply.imp", "imp" +"application/vnd.acucobol", "acu" +"application/vnd.acucorp", "atc" +"application/vnd.adobe.air-application-installer-package+zip", "air" +"application/vnd.adobe.formscentral.fcdt", "fcdt" +"application/vnd.adobe.fxp", "fxp" +"application/vnd.adobe.xdp+xml", "xdp" +"application/vnd.adobe.xfdf", "xfdf" +"application/vnd.ahead.space", "ahead" +"application/vnd.airzip.filesecure.azf", "azf" +"application/vnd.airzip.filesecure.azs", "azs" +"application/vnd.amazon.ebook", "azw" +"application/vnd.americandynamics.acc", "acc" +"application/vnd.amiga.ami", "ami" +"application/vnd.android.package-archive", "apk" +"application/vnd.anser-web-certificate-issue-initiation", "cii" +"application/vnd.anser-web-funds-transfer-initiation", "fti" +"application/vnd.antix.game-component", "atx" +"application/vnd.apple.installer+xml", "mpkg" +"application/vnd.apple.mpegurl", "m3u8" +"application/vnd.aristanetworks.swi", "swi" +"application/vnd.astraea-software.iota", "iota" +"application/vnd.audiograph", "aep" +"application/vnd.blueice.multipass", "mpm" +"application/vnd.bmi", "bmi" +"application/vnd.businessobjects", "rep" +"application/vnd.chemdraw+xml", "cdxml" +"application/vnd.chipnuts.karaoke-mmd", "mmd" +"application/vnd.cinderella", "cdy" +"application/vnd.claymore", "cla" +"application/vnd.cloanto.rp9", "rp9" +"application/vnd.clonk.c4group", "c4g" +"application/vnd.cluetrust.cartomobile-config", "c11amc" +"application/vnd.cluetrust.cartomobile-config-pkg", "c11amz" +"application/vnd.commonspace", "csp" +"application/vnd.contact.cmsg", "cdbcmsg" +"application/vnd.cosmocaller", "cmc" +"application/vnd.crick.clicker", "clkx" +"application/vnd.crick.clicker.keyboard", "clkk" +"application/vnd.crick.clicker.palette", "clkp" +"application/vnd.crick.clicker.template", "clkt" +"application/vnd.crick.clicker.wordbank", "clkw" +"application/vnd.criticaltools.wbs+xml", "wbs" +"application/vnd.ctc-posml", "pml" +"application/vnd.cups-ppd", "ppd" +"application/vnd.curl.car", "car" +"application/vnd.curl.pcurl", "pcurl" +"application/vnd.dart", "dart" +"application/vnd.data-vision.rdz", "rdz" +"application/vnd.dece.data", "uvf" +"application/vnd.dece.ttml+xml", "uvt" +"application/vnd.dece.unspecified", "uvx" +"application/vnd.dece.zip", "uvz" +"application/vnd.denovo.fcselayout-link", "fe_launch" +"application/vnd.dna", "dna" +"application/vnd.dolby.mlp", "mlp" +"application/vnd.dpgraph", "dpg" +"application/vnd.dreamfactory", "dfac" +"application/vnd.ds-keypoint", "kpxx" +"application/vnd.dvb.ait", "ait" +"application/vnd.dvb.service", "svc" +"application/vnd.dynageo", "geo" +"application/vnd.ecowin.chart", "mag" +"application/vnd.enliven", "nml" +"application/vnd.epson.esf", "esf" +"application/vnd.epson.msf", "msf" +"application/vnd.epson.quickanime", "qam" +"application/vnd.epson.salt", "slt" +"application/vnd.epson.ssf", "ssf" +"application/vnd.eszigno3+xml", "es3" +"application/vnd.ezpix-album", "ez2" +"application/vnd.ezpix-package", "ez3" +"application/vnd.fdf", "fdf" +"application/vnd.fdsn.mseed", "mseed" +"application/vnd.fdsn.seed", "seed" +"application/vnd.flographit", "gph" +"application/vnd.fluxtime.clip", "ftc" +"application/vnd.framemaker", "fm" +"application/vnd.frogans.fnc", "fnc" +"application/vnd.frogans.ltf", "ltf" +"application/vnd.fsc.weblaunch", "fsc" +"application/vnd.fujitsu.oasys", "oas" +"application/vnd.fujitsu.oasys2", "oa2" +"application/vnd.fujitsu.oasys3", "oa3" +"application/vnd.fujitsu.oasysgp", "fg5" +"application/vnd.fujitsu.oasysprs", "bh2" +"application/vnd.fujixerox.ddd", "ddd" +"application/vnd.fujixerox.docuworks", "xdw" +"application/vnd.fujixerox.docuworks.binder", "xbd" +"application/vnd.fuzzysheet", "fzs" +"application/vnd.genomatix.tuxedo", "txd" +"application/vnd.geogebra.file", "ggb" +"application/vnd.geogebra.tool", "ggt" +"application/vnd.geometry-explorer", "gex" +"application/vnd.geonext", "gxt" +"application/vnd.geoplan", "g2w" +"application/vnd.geospace", "g3w" +"application/vnd.gmx", "gmx" +"application/vnd.google-earth.kml+xml", "kml" +"application/vnd.google-earth.kmz", "kmz" +"application/vnd.grafeq", "gqf" +"application/vnd.groove-account", "gac" +"application/vnd.groove-help", "ghf" +"application/vnd.groove-identity-message", "gim" +"application/vnd.groove-injector", "grv" +"application/vnd.groove-tool-message", "gtm" +"application/vnd.groove-tool-template", "tpl" +"application/vnd.groove-vcard", "vcg" +"application/vnd.hal+xml", "hal" +"application/vnd.handheld-entertainment+xml", "zmm" +"application/vnd.hbci", "hbci" +"application/vnd.hhe.lesson-player", "les" +"application/vnd.hp-hpgl", "hpgl" +"application/vnd.hp-hpid", "hpid" +"application/vnd.hp-hps", "hps" +"application/vnd.hp-jlyt", "jlt" +"application/vnd.hp-pcl", "pcl" +"application/vnd.hp-pclxl", "pclxl" +"application/vnd.hydrostatix.sof-data", "sfd-hdstx" +"application/vnd.ibm.minipay", "mpy" +"application/vnd.ibm.modcap", "afp" +"application/vnd.ibm.rights-management", "irm" +"application/vnd.ibm.secure-container", "sc" +"application/vnd.iccprofile", "icc" +"application/vnd.igloader", "igl" +"application/vnd.immervision-ivp", "ivp" +"application/vnd.immervision-ivu", "ivu" +"application/vnd.insors.igm", "igm" +"application/vnd.intercon.formnet", "xpw" +"application/vnd.intergeo", "i2g" +"application/vnd.intu.qbo", "qbo" +"application/vnd.intu.qfx", "qfx" +"application/vnd.ipunplugged.rcprofile", "rcprofile" +"application/vnd.irepository.package+xml", "irp" +"application/vnd.is-xpr", "xpr" +"application/vnd.isac.fcs", "fcs" +"application/vnd.jam", "jam" +"application/vnd.jcp.javame.midlet-rms", "rms" +"application/vnd.jisp", "jisp" +"application/vnd.joost.joda-archive", "joda" +"application/vnd.kahootz", "ktz" +"application/vnd.kde.karbon", "karbon" +"application/vnd.kde.kchart", "chrt" +"application/vnd.kde.kformula", "kfo" +"application/vnd.kde.kivio", "flw" +"application/vnd.kde.kontour", "kon" +"application/vnd.kde.kpresenter", "kpr" +"application/vnd.kde.kspread", "ksp" +"application/vnd.kde.kword", "kwd" +"application/vnd.kenameaapp", "htke" +"application/vnd.kidspiration", "kia" +"application/vnd.kinar", "kne" +"application/vnd.koan", "skp" +"application/vnd.kodak-descriptor", "sse" +"application/vnd.las.las+xml", "lasxml" +"application/vnd.llamagraphics.life-balance.desktop", "lbd" +"application/vnd.llamagraphics.life-balance.exchange+xml", "lbe" +"application/vnd.lotus-1-2-3", "123" +"application/vnd.lotus-approach", "apr" +"application/vnd.lotus-freelance", "pre" +"application/vnd.lotus-notes", "nsf" +"application/vnd.lotus-organizer", "org" +"application/vnd.lotus-screencam", "scm" +"application/vnd.lotus-wordpro", "lwp" +"application/vnd.macports.portpkg", "portpkg" +"application/vnd.mcd", "mcd" +"application/vnd.medcalcdata", "mc1" +"application/vnd.mediastation.cdkey", "cdkey" +"application/vnd.mfer", "mwf" +"application/vnd.mfmp", "mfm" +"application/vnd.micrografx.flo", "flo" +"application/vnd.micrografx.igx", "igx" +"application/vnd.mif", "mif" +"application/vnd.mobius.daf", "daf" +"application/vnd.mobius.dis", "dis" +"application/vnd.mobius.mbk", "mbk" +"application/vnd.mobius.mqy", "mqy" +"application/vnd.mobius.msl", "msl" +"application/vnd.mobius.plc", "plc" +"application/vnd.mobius.txf", "txf" +"application/vnd.mophun.application", "mpn" +"application/vnd.mophun.certificate", "mpc" +"application/vnd.mozilla.xul+xml", "xul" +"application/vnd.ms-artgalry", "cil" +"application/vnd.ms-cab-compressed", "cab" +"application/vnd.ms-excel", "xls" +"application/vnd.ms-excel.addin.macroenabled.12", "xlam" +"application/vnd.ms-excel.sheet.binary.macroenabled.12", "xlsb" +"application/vnd.ms-excel.sheet.macroenabled.12", "xlsm" +"application/vnd.ms-excel.template.macroenabled.12", "xltm" +"application/vnd.ms-fontobject", "eot" +"application/vnd.ms-htmlhelp", "chm" +"application/vnd.ms-ims", "ims" +"application/vnd.ms-lrm", "lrm" +"application/vnd.ms-officetheme", "thmx" +"application/vnd.ms-pki.seccat", "cat" +"application/vnd.ms-pki.stl", "stl" +"application/vnd.ms-powerpoint", "ppt" +"application/vnd.ms-powerpoint.addin.macroenabled.12", "ppam" +"application/vnd.ms-powerpoint.presentation.macroenabled.12", "pptm" +"application/vnd.ms-powerpoint.slide.macroenabled.12", "sldm" +"application/vnd.ms-powerpoint.slideshow.macroenabled.12", "ppsm" +"application/vnd.ms-powerpoint.template.macroenabled.12", "potm" +"application/vnd.ms-project", "mpp" +"application/vnd.ms-word.document.macroenabled.12", "docm" +"application/vnd.ms-word.template.macroenabled.12", "dotm" +"application/vnd.ms-works", "wps" +"application/vnd.ms-wpl", "wpl" +"application/vnd.ms-xpsdocument", "xps" +"application/vnd.mseq", "mseq" +"application/vnd.musician", "mus" +"application/vnd.muvee.style", "msty" +"application/vnd.mynfc", "taglet" +"application/vnd.neurolanguage.nlu", "nlu" +"application/vnd.nitf", "ntf" +"application/vnd.noblenet-directory", "nnd" +"application/vnd.noblenet-sealer", "nns" +"application/vnd.noblenet-web", "nnw" +"application/vnd.nokia.n-gage.data", "ngdat" +"application/vnd.nokia.n-gage.symbian.install", "n-gage" +"application/vnd.nokia.radio-preset", "rpst" +"application/vnd.nokia.radio-presets", "rpss" +"application/vnd.novadigm.edm", "edm" +"application/vnd.novadigm.edx", "edx" +"application/vnd.novadigm.ext", "ext" +"application/vnd.oasis.opendocument.chart", "odc" +"application/vnd.oasis.opendocument.chart-template", "otc" +"application/vnd.oasis.opendocument.database", "odb" +"application/vnd.oasis.opendocument.formula", "odf" +"application/vnd.oasis.opendocument.formula-template", "odft" +"application/vnd.oasis.opendocument.graphics", "odg" +"application/vnd.oasis.opendocument.graphics-template", "otg" +"application/vnd.oasis.opendocument.image", "odi" +"application/vnd.oasis.opendocument.image-template", "oti" +"application/vnd.oasis.opendocument.presentation", "odp" +"application/vnd.oasis.opendocument.presentation-template", "otp" +"application/vnd.oasis.opendocument.spreadsheet", "ods" +"application/vnd.oasis.opendocument.spreadsheet-template", "ots" +"application/vnd.oasis.opendocument.text", "odt" +"application/vnd.oasis.opendocument.text-master", "odm" +"application/vnd.oasis.opendocument.text-template", "ott" +"application/vnd.oasis.opendocument.text-web", "oth" +"application/vnd.olpc-sugar", "xo" +"application/vnd.oma.dd2+xml", "dd2" +"application/vnd.openofficeorg.extension", "oxt" +"application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx" +"application/vnd.openxmlformats-officedocument.presentationml.slide", "sldx" +"application/vnd.openxmlformats-officedocument.presentationml.slideshow", "ppsx" +"application/vnd.openxmlformats-officedocument.presentationml.template", "potx" +"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx" +"application/vnd.openxmlformats-officedocument.spreadsheetml.template", "xltx" +"application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx" +"application/vnd.openxmlformats-officedocument.wordprocessingml.template", "dotx" +"application/vnd.osgeo.mapguide.package", "mgp" +"application/vnd.osgi.dp", "dp" +"application/vnd.osgi.subsystem", "esa" +"application/vnd.palm", "pdb" +"application/vnd.pawaafile", "paw" +"application/vnd.pg.format", "str" +"application/vnd.pg.osasli", "ei6" +"application/vnd.picsel", "efif" +"application/vnd.pmi.widget", "wg" +"application/vnd.pocketlearn", "plf" +"application/vnd.powerbuilder6", "pbd" +"application/vnd.previewsystems.box", "box" +"application/vnd.proteus.magazine", "mgz" +"application/vnd.publishare-delta-tree", "qps" +"application/vnd.pvi.ptid1", "ptid" +"application/vnd.quark.quarkxpress", "qxd" +"application/vnd.realvnc.bed", "bed" +"application/vnd.recordare.musicxml", "mxl" +"application/vnd.recordare.musicxml+xml", "musicxml" +"application/vnd.rig.cryptonote", "cryptonote" +"application/vnd.rim.cod", "cod" +"application/vnd.rn-realmedia", "rm" +"application/vnd.rn-realmedia-vbr", "rmvb" +"application/vnd.route66.link66+xml", "link66" +"application/vnd.sailingtracker.track", "st" +"application/vnd.seemail", "see" +"application/vnd.sema", "sema" +"application/vnd.semd", "semd" +"application/vnd.semf", "semf" +"application/vnd.shana.informed.formdata", "ifm" +"application/vnd.shana.informed.formtemplate", "itp" +"application/vnd.shana.informed.interchange", "iif" +"application/vnd.shana.informed.package", "ipk" +"application/vnd.simtech-mindmapper", "twd" +"application/vnd.smaf", "mmf" +"application/vnd.smart.teacher", "teacher" +"application/vnd.solent.sdkm+xml", "sdkm" +"application/vnd.spotfire.dxp", "dxp" +"application/vnd.spotfire.sfs", "sfs" +"application/vnd.stardivision.calc", "sdc" +"application/vnd.stardivision.draw", "sda" +"application/vnd.stardivision.impress", "sdd" +"application/vnd.stardivision.math", "smf" +"application/vnd.stardivision.writer", "sdw" +"application/vnd.stardivision.writer-global", "sgl" +"application/vnd.stepmania.package", "smzip" +"application/vnd.stepmania.stepchart", "sm" +"application/vnd.sun.xml.calc", "sxc" +"application/vnd.sun.xml.calc.template", "stc" +"application/vnd.sun.xml.draw", "sxd" +"application/vnd.sun.xml.draw.template", "std" +"application/vnd.sun.xml.impress", "sxi" +"application/vnd.sun.xml.impress.template", "sti" +"application/vnd.sun.xml.math", "sxm" +"application/vnd.sun.xml.writer", "sxw" +"application/vnd.sun.xml.writer.global", "sxg" +"application/vnd.sun.xml.writer.template", "stw" +"application/vnd.sus-calendar", "sus" +"application/vnd.svd", "svd" +"application/vnd.symbian.install", "sis" +"application/vnd.syncml+xml", "xsm" +"application/vnd.syncml.dm+wbxml", "bdm" +"application/vnd.syncml.dm+xml", "xdm" +"application/vnd.tao.intent-module-archive", "tao" +"application/vnd.tcpdump.pcap", "pcap" +"application/vnd.tmobile-livetv", "tmo" +"application/vnd.trid.tpt", "tpt" +"application/vnd.triscape.mxs", "mxs" +"application/vnd.trueapp", "tra" +"application/vnd.ufdl", "ufd" +"application/vnd.uiq.theme", "utz" +"application/vnd.umajin", "umj" +"application/vnd.unity", "unityweb" +"application/vnd.uoml+xml", "uoml" +"application/vnd.vcx", "vcx" +"application/vnd.visio", "vsd" +"application/vnd.visionary", "vis" +"application/vnd.vsf", "vsf" +"application/vnd.wap.wbxml", "wbxml" +"application/vnd.wap.wmlc", "wmlc" +"application/vnd.wap.wmlscriptc", "wmlsc" +"application/vnd.webturbo", "wtb" +"application/vnd.wolfram.player", "nbp" +"application/vnd.wordperfect", "wpd" +"application/vnd.wqd", "wqd" +"application/vnd.wt.stf", "stf" +"application/vnd.xara", "xar" +"application/vnd.xfdl", "xfdl" +"application/vnd.yamaha.hv-dic", "hvd" +"application/vnd.yamaha.hv-script", "hvs" +"application/vnd.yamaha.hv-voice", "hvp" +"application/vnd.yamaha.openscoreformat", "osf" +"application/vnd.yamaha.openscoreformat.osfpvg+xml", "osfpvg" +"application/vnd.yamaha.smaf-audio", "saf" +"application/vnd.yamaha.smaf-phrase", "spf" +"application/vnd.yellowriver-custom-menu", "cmp" +"application/vnd.zul", "zir" +"application/vnd.zzazz.deck+xml", "zaz" +"application/voicexml+xml", "vxml" +"application/widget", "wgt" +"application/winhlp", "hlp" +"application/wsdl+xml", "wsdl" +"application/wspolicy+xml", "wspolicy" +"application/x-7z-compressed", "7z" +"application/x-abiword", "abw" +"application/x-ace-compressed", "ace" +"application/x-apple-diskimage", "dmg" +"application/x-authorware-bin", "aab" +"application/x-authorware-map", "aam" +"application/x-authorware-seg", "aas" +"application/x-bcpio", "bcpio" +"application/x-bittorrent", "torrent" +"application/x-blorb", "blb" +"application/x-bzip", "bz" +"application/x-bzip2", "bz2" +"application/x-cbr", "cbr" +"application/x-cdlink", "vcd" +"application/x-cfs-compressed", "cfs" +"application/x-chat", "chat" +"application/x-chess-pgn", "pgn" +"application/x-conference", "nsc" +"application/x-cpio", "cpio" +"application/x-csh", "csh" +"application/x-debian-package", "deb" +"application/x-dgc-compressed", "dgc" +"application/x-director", "dir" +"application/x-doom", "wad" +"application/x-dtbncx+xml", "ncx" +"application/x-dtbook+xml", "dtb" +"application/x-dtbresource+xml", "res" +"application/x-dvi", "dvi" +"application/x-envoy", "evy" +"application/x-eva", "eva" +"application/x-font-bdf", "bdf" +"application/x-font-ghostscript", "gsf" +"application/x-font-linux-psf", "psf" +"application/x-font-otf", "otf" +"application/x-font-pcf", "pcf" +"application/x-font-snf", "snf" +"application/x-font-ttf", "ttf" +"application/x-font-type1", "pfa" +"application/x-freearc", "arc" +"application/x-futuresplash", "spl" +"application/x-gca-compressed", "gca" +"application/x-glulx", "ulx" +"application/x-gnumeric", "gnumeric" +"application/x-gramps-xml", "gramps" +"application/x-gtar", "gtar" +"application/x-hdf", "hdf" +"application/x-install-instructions", "install" +"application/x-iso9660-image", "iso" +"application/x-java-jnlp-file", "jnlp" +"application/x-latex", "latex" +"application/x-lzh-compressed", "lzh" +"application/x-mie", "mie" +"application/x-mobipocket-ebook", "prc" +"application/x-ms-application", "application" +"application/x-ms-shortcut", "lnk" +"application/x-ms-wmd", "wmd" +"application/x-ms-wmz", "wmz" +"application/x-ms-xbap", "xbap" +"application/x-msaccess", "mdb" +"application/x-msbinder", "obd" +"application/x-mscardfile", "crd" +"application/x-msclip", "clp" +"application/x-msdownload", "exe" +"application/x-msmediaview", "mvb" +"application/x-msmetafile", "wmf" +"application/x-msmoney", "mny" +"application/x-mspublisher", "pub" +"application/x-msschedule", "scd" +"application/x-msterminal", "trm" +"application/x-mswrite", "wri" +"application/x-netcdf", "nc" +"application/x-nzb", "nzb" +"application/x-pkcs12", "p12" +"application/x-pkcs7-certificates", "p7b" +"application/x-pkcs7-certreqresp", "p7r" +"application/x-rar-compressed", "rar" +"application/x-research-info-systems", "ris" +"application/x-sh", "sh" +"application/x-shar", "shar" +"application/x-shockwave-flash", "swf" +"application/x-silverlight-app", "xap" +"application/x-sql", "sql" +"application/x-stuffit", "sit" +"application/x-stuffitx", "sitx" +"application/x-subrip", "srt" +"application/x-sv4cpio", "sv4cpio" +"application/x-sv4crc", "sv4crc" +"application/x-t3vm-image", "t3" +"application/x-tads", "gam" +"application/x-tar", "tar" +"application/x-tcl", "tcl" +"application/x-tex", "tex" +"application/x-tex-tfm", "tfm" +"application/x-texinfo", "texinfo" +"application/x-tgif", "obj" +"application/x-ustar", "ustar" +"application/x-wais-source", "src" +"application/x-x509-ca-cert", "der" +"application/x-xfig", "fig" +"application/x-xliff+xml", "xlf" +"application/x-xpinstall", "xpi" +"application/x-xz", "xz" +"application/x-zmachine", "z1" +"application/xaml+xml", "xaml" +"application/xcap-diff+xml", "xdf" +"application/xenc+xml", "xenc" +"application/xhtml+xml", "xhtml" +"application/xml", "xml" +"application/xml-dtd", "dtd" +"application/xop+xml", "xop" +"application/xproc+xml", "xpl" +"application/xslt+xml", "xslt" +"application/xspf+xml", "xspf" +"application/xv+xml", "mxml" +"application/yang", "yang" +"application/yin+xml", "yin" +"application/zip", "zip" +"audio/adpcm", "adp" +"audio/basic", "au" +"audio/midi", "midi" +"audio/mp4", "mp4a" +"audio/mpeg", "mp3" +"audio/ogg", "oga" +"audio/s3m", "s3m" +"audio/silk", "sil" +"audio/vnd.dece.audio", "uva" +"audio/vnd.digital-winds", "eol" +"audio/vnd.dra", "dra" +"audio/vnd.dts", "dts" +"audio/vnd.dts.hd", "dtshd" +"audio/vnd.lucent.voice", "lvp" +"audio/vnd.ms-playready.media.pya", "pya" +"audio/vnd.nuera.ecelp4800", "ecelp4800" +"audio/vnd.nuera.ecelp7470", "ecelp7470" +"audio/vnd.nuera.ecelp9600", "ecelp9600" +"audio/vnd.rip", "rip" +"audio/webm", "weba" +"audio/x-aac", "aac" +"audio/x-aiff", "aif" +"audio/x-caf", "caf" +"audio/x-flac", "flac" +"audio/x-matroska", "mka" +"audio/x-mpegurl", "m3u" +"audio/x-ms-wax", "wax" +"audio/x-ms-wma", "wma" +"audio/x-pn-realaudio", "ram" +"audio/x-pn-realaudio-plugin", "rmp" +"audio/x-wav", "wav" +"audio/xm", "xm" +"chemical/x-cdx", "cdx" +"chemical/x-cif", "cif" +"chemical/x-cmdf", "cmdf" +"chemical/x-cml", "cml" +"chemical/x-csml", "csml" +"chemical/x-xyz", "xyz" +"image/bmp", "bmp" +"image/cgm", "cgm" +"image/g3fax", "g3" +"image/gif", "gif" +"image/ief", "ief" +"image/jpeg", "jpg" +"image/ktx", "ktx" +"image/png", "png" +"image/prs.btif", "btif" +"image/sgi", "sgi" +"image/svg+xml", "svg" +"image/tiff", "tiff" +"image/vnd.adobe.photoshop", "psd" +"image/vnd.dece.graphic", "uvi" +"image/vnd.djvu", "djvu" +"image/vnd.dvb.subtitle", "sub" +"image/vnd.dwg", "dwg" +"image/vnd.dxf", "dxf" +"image/vnd.fastbidsheet", "fbs" +"image/vnd.fpx", "fpx" +"image/vnd.fst", "fst" +"image/vnd.fujixerox.edmics-mmr", "mmr" +"image/vnd.fujixerox.edmics-rlc", "rlc" +"image/vnd.ms-modi", "mdi" +"image/vnd.ms-photo", "wdp" +"image/vnd.net-fpx", "npx" +"image/vnd.wap.wbmp", "wbmp" +"image/vnd.xiff", "xif" +"image/webp", "webp" +"image/x-3ds", "3ds" +"image/x-cmu-raster", "ras" +"image/x-cmx", "cmx" +"image/x-freehand", "fh" +"image/x-icon", "ico" +"image/x-mrsid-image", "sid" +"image/x-pcx", "pcx" +"image/x-pict", "pic" +"image/x-portable-anymap", "pnm" +"image/x-portable-bitmap", "pbm" +"image/x-portable-graymap", "pgm" +"image/x-portable-pixmap", "ppm" +"image/x-rgb", "rgb" +"image/x-tga", "tga" +"image/x-xbitmap", "xbm" +"image/x-xpixmap", "xpm" +"image/x-xwindowdump", "xwd" +"message/rfc822", "eml" +"model/iges", "igs" +"model/mesh", "msh" +"model/vnd.collada+xml", "dae" +"model/vnd.dwf", "dwf" +"model/vnd.gdl", "gdl" +"model/vnd.gtw", "gtw" +"model/vnd.mts", "mts" +"model/vnd.vtu", "vtu" +"model/vrml", "wrl" +"model/x3d+binary", "x3db" +"model/x3d+vrml", "x3dv" +"model/x3d+xml", "x3d" +"text/cache-manifest", "appcache" +"text/calendar", "ics" +"text/css", "css" +"text/csv", "csv" +"text/html", "html" +"text/n3", "n3" +"text/plain", "txt" +"text/prs.lines.tag", "dsc" +"text/richtext", "rtx" +"text/sgml", "sgml" +"text/tab-separated-values", "tsv" +"text/troff", "t" +"text/turtle", "ttl" +"text/uri-list", "uri" +"text/vcard", "vcard" +"text/vnd.curl", "curl" +"text/vnd.curl.dcurl", "dcurl" +"text/vnd.curl.mcurl", "mcurl" +"text/vnd.curl.scurl", "scurl" +"text/vnd.dvb.subtitle", "sub" +"text/vnd.fly", "fly" +"text/vnd.fmi.flexstor", "flx" +"text/vnd.graphviz", "gv" +"text/vnd.in3d.3dml", "3dml" +"text/vnd.in3d.spot", "spot" +"text/vnd.sun.j2me.app-descriptor", "jad" +"text/vnd.wap.wml", "wml" +"text/vnd.wap.wmlscript", "wmls" +"text/x-asm", "asm" +"text/x-c", "c" +"text/x-fortran", "f" +"text/x-java-source", "java" +"text/x-nfo", "nfo" +"text/x-opml", "opml" +"text/x-pascal", "pas" +"text/x-setext", "etx" +"text/x-sfv", "sfv" +"text/x-uuencode", "uu" +"text/x-vcalendar", "vcs" +"text/x-vcard", "vcf" +"video/3gpp", "3gp" +"video/3gpp2", "3g2" +"video/h261", "h261" +"video/h263", "h263" +"video/h264", "h264" +"video/jpeg", "jpgv" +"video/jpm", "jpm" +"video/mj2", "mj2" +"video/mp4", "mp4" +"video/mpeg", "mpeg" +"video/ogg", "ogv" +"video/quicktime", "mov" +"video/vnd.dece.hd", "uvh" +"video/vnd.dece.mobile", "uvm" +"video/vnd.dece.pd", "uvp" +"video/vnd.dece.sd", "uvs" +"video/vnd.dece.video", "uvv" +"video/vnd.dvb.file", "dvb" +"video/vnd.fvt", "fvt" +"video/vnd.mpegurl", "mxu" +"video/vnd.ms-playready.media.pyv", "pyv" +"video/vnd.uvvu.mp4", "uvu" +"video/vnd.vivo", "viv" +"video/webm", "webm" +"video/x-f4v", "f4v" +"video/x-fli", "fli" +"video/x-flv", "flv" +"video/x-m4v", "m4v" +"video/x-matroska", "mkv" +"video/x-mng", "mng" +"video/x-ms-asf", "asf" +"video/x-ms-vob", "vob" +"video/x-ms-wm", "wm" +"video/x-ms-wmv", "wmv" +"video/x-ms-wmx", "wmx" +"video/x-ms-wvx", "wvx" +"video/x-msvideo", "avi" +"video/x-sgi-movie", "movie" +"video/x-smv", "smv" +"x-conference/x-cooltalk", "ice" +%% +const char *mime_type_to_extension(const char *mime_type, size_t mime_type_len) { + const auto &result = search_mime_type(mime_type, mime_type_len); + if (result == nullptr) { + return nullptr; + } + + return result->extension; +} diff --git a/submodules/ton/tonlib-src/tdutils/td/utils/AtomicRead.h b/submodules/ton/tonlib-src/tdutils/td/utils/AtomicRead.h new file mode 100644 index 00000000000..0eb85c6dc29 --- /dev/null +++ b/submodules/ton/tonlib-src/tdutils/td/utils/AtomicRead.h @@ -0,0 +1,90 @@ +/* + This file is part of TON Blockchain source code. + + TON Blockchain is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + TON Blockchain is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with TON Blockchain. If not, see . + + In addition, as a special exception, the copyright holders give permission + to link the code of portions of this program with the OpenSSL library. + You must obey the GNU General Public License in all respects for all + of the code used other than OpenSSL. If you modify file(s) with this + exception, you may extend this exception to your version of the file(s), + but you are not obligated to do so. If you do not wish to do so, delete this + exception statement from your version. If you delete this exception statement + from all source files in the program, then also delete it here. + + Copyright 2019-2020 Telegram Systems LLP +*/ +#include + +#include "td/utils/common.h" +#include "td/utils/port/thread.h" +namespace td { +template + +class AtomicRead { + public: + void read(T &dest) const { + while (true) { + static_assert(std::is_trivially_copyable::value, "T must be trivially copyable"); + auto version_before = version.load(); + memcpy(&dest, &value, sizeof(dest)); + auto version_after = version.load(); + if (version_before == version_after && version_before % 2 == 0) { + break; + } + td::this_thread::yield(); + } + } + + friend struct Write; + struct Write { + explicit Write(AtomicRead *read) { + read->do_lock(); + ptr.reset(read); + } + struct Destructor { + void operator()(AtomicRead *read) const { + read->do_unlock(); + } + }; + T &operator*() { + return value(); + } + T *operator->() { + return &value(); + } + T &value() { + CHECK(ptr); + return ptr->value; + } + + private: + std::unique_ptr ptr; + }; + Write lock() { + return Write(this); + } + + private: + std::atomic version{0}; + T value; + + void do_lock() { + CHECK(++version % 2 == 1); + } + void do_unlock() { + CHECK(++version % 2 == 0); + } +}; +}; // namespace td diff --git a/submodules/ton/tonlib-src/tdutils/td/utils/Status.h b/submodules/ton/tonlib-src/tdutils/td/utils/Status.h index 8016099fa70..a9879996d46 100644 --- a/submodules/ton/tonlib-src/tdutils/td/utils/Status.h +++ b/submodules/ton/tonlib-src/tdutils/td/utils/Status.h @@ -57,6 +57,15 @@ } \ } +#define TRY_STATUS_PROMISE_PREFIX(promise_name, status, prefix) \ + { \ + auto try_status = (status); \ + if (try_status.is_error()) { \ + promise_name.set_error(try_status.move_as_error_prefix(prefix)); \ + return; \ + } \ + } + #define TRY_RESULT(name, result) TRY_RESULT_IMPL(TD_CONCAT(TD_CONCAT(r_, name), __LINE__), auto name, result) #define TRY_RESULT_PROMISE(promise_name, name, result) \ @@ -437,6 +446,7 @@ class Status { template class Result { public: + using ValueT = T; Result() : status_(Status::Error<-1>()) { } template , Result>::value, int> = 0> diff --git a/submodules/ton/tonlib-src/tdutils/test/StealingQueue.cpp b/submodules/ton/tonlib-src/tdutils/test/StealingQueue.cpp index 6aa2aae6ba9..c5ff8b5184a 100644 --- a/submodules/ton/tonlib-src/tdutils/test/StealingQueue.cpp +++ b/submodules/ton/tonlib-src/tdutils/test/StealingQueue.cpp @@ -28,6 +28,7 @@ #include "td/utils/tests.h" #include "td/utils/benchmark.h" +#include "td/utils/AtomicRead.h" #include "td/utils/StealingQueue.h" #include "td/utils/MpmcQueue.h" @@ -79,6 +80,46 @@ TEST(AtomicRead, simple) { thread.join(); } } +TEST(AtomicRead, simple2) { + td::Stage run; + td::Stage check; + + size_t threads_n = 10; + std::vector threads; + + struct Value { + td::uint64 value = 0; + char str[50] = "0 0 0 0"; + }; + AtomicRead value; + + auto to_str = [](size_t i) { return PSTRING() << i << " " << i << " " << i << " " << i; }; + for (size_t i = 0; i < threads_n; i++) { + threads.push_back(td::thread([&, id = static_cast(i)] { + for (uint64 round = 1; round < 10000; round++) { + if (id == 0) { + } + run.wait(round * threads_n); + if (id == 0) { + auto x = value.lock(); + x->value = round; + auto str = to_str(round); + memcpy(x->str, str.c_str(), str.size() + 1); + } else { + Value x; + value.read(x); + LOG_CHECK(x.value == round || x.value == round - 1) << x.value << " " << round; + CHECK(x.str == to_str(x.value)); + } + check.wait(round * threads_n); + } + })); + } + for (auto &thread : threads) { + thread.join(); + } +} + TEST(StealingQueue, simple) { uint64 sum; std::atomic got_sum; diff --git a/submodules/ton/tonlib-src/third-party/crc32c/.appveyor.yml b/submodules/ton/tonlib-src/third-party/crc32c/.appveyor.yml index 7345746750a..52d0c273cf8 100644 --- a/submodules/ton/tonlib-src/third-party/crc32c/.appveyor.yml +++ b/submodules/ton/tonlib-src/third-party/crc32c/.appveyor.yml @@ -20,6 +20,9 @@ configuration: - RelWithDebInfo - Debug +build: + verbosity: minimal + build_script: - git submodule update --init --recursive - mkdir build diff --git a/submodules/ton/tonlib-src/third-party/crc32c/.gitignore b/submodules/ton/tonlib-src/third-party/crc32c/.gitignore index 61769727e31..747a664ab9f 100644 --- a/submodules/ton/tonlib-src/third-party/crc32c/.gitignore +++ b/submodules/ton/tonlib-src/third-party/crc32c/.gitignore @@ -1,7 +1,6 @@ # Editors. *.sw* .DS_Store -/.vscode # Build directory. build/ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/.travis.yml b/submodules/ton/tonlib-src/third-party/crc32c/.travis.yml index 9edf24c5f54..bc9dd703d78 100644 --- a/submodules/ton/tonlib-src/third-party/crc32c/.travis.yml +++ b/submodules/ton/tonlib-src/third-party/crc32c/.travis.yml @@ -1,61 +1,48 @@ -# Build matrix / environment variables are explained on: +# Build matrix / environment variable are explained on: # http://about.travis-ci.org/docs/user/build-configuration/ # This file can be validated on: http://lint.travis-ci.org/ +sudo: false +dist: trusty language: cpp -dist: xenial -osx_image: xcode10.2 compiler: -- gcc -- clang + - gcc + - clang os: -- linux -- osx + - linux + - osx env: -- GLOG=1 SHARED_LIB=0 BUILD_TYPE=Debug -- GLOG=1 SHARED_LIB=0 BUILD_TYPE=RelWithDebInfo -- GLOG=0 SHARED_LIB=0 BUILD_TYPE=Debug -- GLOG=0 SHARED_LIB=0 BUILD_TYPE=RelWithDebInfo -- GLOG=0 SHARED_LIB=1 BUILD_TYPE=Debug -- GLOG=0 SHARED_LIB=1 BUILD_TYPE=RelWithDebInfo + - GLOG=1 BUILD_TYPE=Debug + - GLOG=1 BUILD_TYPE=RelWithDebInfo + - GLOG=0 BUILD_TYPE=Debug + - GLOG=0 BUILD_TYPE=RelWithDebInfo addons: apt: + # List of whitelisted in travis packages for ubuntu-trusty can be found here: + # https://github.com/travis-ci/apt-package-whitelist/blob/master/ubuntu-trusty + # List of whitelisted in travis apt-sources: + # https://github.com/travis-ci/apt-source-whitelist/blob/master/ubuntu.json sources: - - llvm-toolchain-xenial-8 - ubuntu-toolchain-r-test + - llvm-toolchain-trusty-6.0 packages: - - clang-8 - cmake - - gcc-9 - - g++-9 - - ninja-build - homebrew: - packages: - - cmake - - gcc@9 - - llvm@8 - - ninja - update: true + - gcc-8 + - g++-8 + - clang-6.0 install: -# The following Homebrew packages aren't linked by default, and need to be -# prepended to the path explicitly. -- if [ "$TRAVIS_OS_NAME" == "osx" ]; then - export PATH="$(brew --prefix llvm)/bin:$PATH"; - fi -# /usr/bin/gcc points to an older compiler on both Linux and macOS. -- if [ "$CXX" = "g++" ]; then export CXX="g++-9" CC="gcc-9"; fi -# /usr/bin/clang points to an older compiler on both Linux and macOS. -# -# Homebrew's llvm package doesn't ship a versioned clang++ binary, so the values -# below don't work on macOS. Fortunately, the path change above makes the -# default values (clang and clang++) resolve to the correct compiler on macOS. -- if [ "$TRAVIS_OS_NAME" == "linux" ]; then - if [ "$CXX" = "clang++" ]; then export CXX="clang++-8" CC="clang-8"; fi; - fi +# Travis doesn't have a nice way to install homebrew packages yet. +# https://github.com/travis-ci/travis-ci/issues/5377 +- if [ "$TRAVIS_OS_NAME" == "osx" ]; then brew update; fi +# https://github.com/Homebrew/brew/issues/1742 +- if [ "$TRAVIS_OS_NAME" == "osx" ]; then rm -f /usr/local/include/c++ ; fi +- if [ "$TRAVIS_OS_NAME" == "osx" ]; then brew install gcc@8; fi +# /usr/bin/gcc is stuck to old versions by on both Linux and OSX. +- if [ "$CXX" = "g++" ]; then export CXX="g++-8" CC="gcc-8"; fi - echo ${CC} - echo ${CXX} - ${CXX} --version @@ -63,8 +50,7 @@ install: before_script: - mkdir -p build && cd build -- cmake .. -G Ninja -DCRC32C_USE_GLOG=$GLOG -DCMAKE_BUILD_TYPE=$BUILD_TYPE - -DBUILD_SHARED_LIBS=$SHARED_LIB +- cmake .. -DCRC32C_USE_GLOG=$GLOG -DCMAKE_BUILD_TYPE=$BUILD_TYPE - cmake --build . - cd .. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/CMakeLists.txt b/submodules/ton/tonlib-src/third-party/crc32c/CMakeLists.txt index 787a6e31b80..04881e9b661 100644 --- a/submodules/ton/tonlib-src/third-party/crc32c/CMakeLists.txt +++ b/submodules/ton/tonlib-src/third-party/crc32c/CMakeLists.txt @@ -3,7 +3,7 @@ # found in the LICENSE file. See the AUTHORS file for names of contributors. cmake_minimum_required(VERSION 3.1) -project(Crc32c VERSION 1.1.0 LANGUAGES C CXX) +project(Crc32c VERSION 0.1.0 LANGUAGES C CXX) # This project can use C11, but will gracefully decay down to C89. set(CMAKE_C_STANDARD 11) @@ -26,12 +26,12 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") endif(CMAKE_CXX_FLAGS MATCHES "/W[0-4]") # Disable C++ exceptions. - string(REGEX REPLACE "/EH[a-z]+" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + string(REGEX REPLACE "/EH[a-z]+" "" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHs-c-") add_definitions(-D_HAS_EXCEPTIONS=0) # Disable RTTI. - string(REGEX REPLACE "/GR" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + string(REGEX REPLACE "/GR" "" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /GR-") else(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") # Use -Wall for clang and gcc. @@ -50,11 +50,11 @@ else(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") endif(NOT CMAKE_CXX_FLAGS MATCHES "-Werror") # Disable C++ exceptions. - string(REGEX REPLACE "-fexceptions" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + string(REGEX REPLACE "-fexceptions" "" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-exceptions") # Disable RTTI. - string(REGEX REPLACE "-frtti" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + string(REGEX REPLACE "-frtti" "" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti") endif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") @@ -229,11 +229,6 @@ if(HAVE_ARM64_CRC32C) endif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") endif(HAVE_ARM64_CRC32C) -# CMake only enables PIC by default in SHARED and MODULE targets. -if(BUILD_SHARED_LIBS) - set_property(TARGET crc32c_arm64 PROPERTY POSITION_INDEPENDENT_CODE TRUE) -endif(BUILD_SHARED_LIBS) - # SSE4.2 code is built separately, so we don't accidentally compile unsupported # instructions into code that gets run without SSE4.2 support. add_library(crc32c_sse42 OBJECT "") @@ -251,11 +246,6 @@ if(HAVE_SSE42) endif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") endif(HAVE_SSE42) -# CMake only enables PIC by default in SHARED and MODULE targets. -if(BUILD_SHARED_LIBS) - set_property(TARGET crc32c_sse42 PROPERTY POSITION_INDEPENDENT_CODE TRUE) -endif(BUILD_SHARED_LIBS) - add_library(crc32c "" # TODO(pwnall): Move the TARGET_OBJECTS generator expressions to the PRIVATE # section of target_sources when cmake_minimum_required becomes 3.9 or above. @@ -287,9 +277,6 @@ target_include_directories(crc32c $ ) -set_target_properties(crc32c - PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR}) - # Warnings as errors in Visual Studio for this project's targets. if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") set_property(TARGET crc32c APPEND PROPERTY COMPILE_OPTIONS "/WX") diff --git a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_arm64_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_arm64_unittest.cc index 6f917d9c0ce..ea9e84163f7 100644 --- a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_arm64_unittest.cc +++ b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_arm64_unittest.cc @@ -17,7 +17,7 @@ struct Arm64TestTraits { } }; -INSTANTIATE_TYPED_TEST_SUITE_P(Arm64, ExtendTest, Arm64TestTraits); +INSTANTIATE_TYPED_TEST_CASE_P(Arm64, ExtendTest, Arm64TestTraits); #endif // HAVE_ARM64_CRC32C diff --git a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_extend_unittests.h b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_extend_unittests.h index 0732973737d..398a5ef73e8 100644 --- a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_extend_unittests.h +++ b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_extend_unittests.h @@ -18,7 +18,7 @@ namespace crc32c { template class ExtendTest : public testing::Test {}; -TYPED_TEST_SUITE_P(ExtendTest); +TYPED_TEST_CASE_P(ExtendTest); TYPED_TEST_P(ExtendTest, StandardResults) { // From rfc3720 section B.4. @@ -101,7 +101,7 @@ TYPED_TEST_P(ExtendTest, LargeBufferSlicing) { } } -REGISTER_TYPED_TEST_SUITE_P(ExtendTest, +REGISTER_TYPED_TEST_CASE_P(ExtendTest, StandardResults, HelloWorld, BufferSlicing, diff --git a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_portable_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_portable_unittest.cc index 5098e2c373f..7d87d925539 100644 --- a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_portable_unittest.cc +++ b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_portable_unittest.cc @@ -15,6 +15,6 @@ struct PortableTestTraits { } }; -INSTANTIATE_TYPED_TEST_SUITE_P(Portable, ExtendTest, PortableTestTraits); +INSTANTIATE_TYPED_TEST_CASE_P(Portable, ExtendTest, PortableTestTraits); } // namespace crc32c diff --git a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_sse42_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_sse42_unittest.cc index c73ad8ddd16..af2ecc41972 100644 --- a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_sse42_unittest.cc +++ b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_sse42_unittest.cc @@ -17,7 +17,7 @@ struct Sse42TestTraits { } }; -INSTANTIATE_TYPED_TEST_SUITE_P(Sse42, ExtendTest, Sse42TestTraits); +INSTANTIATE_TYPED_TEST_CASE_P(Sse42, ExtendTest, Sse42TestTraits); #endif // HAVE_SSE42 && (defined(_M_X64) || defined(__x86_64__)) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_unittest.cc index d6c6af680c6..e9c97715ede 100644 --- a/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_unittest.cc +++ b/submodules/ton/tonlib-src/third-party/crc32c/src/crc32c_unittest.cc @@ -52,7 +52,7 @@ struct ApiTestTraits { } }; -INSTANTIATE_TYPED_TEST_SUITE_P(Api, ExtendTest, ApiTestTraits); +INSTANTIATE_TYPED_TEST_CASE_P(Api, ExtendTest, ApiTestTraits); } // namespace crc32c diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.clang-format b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.clang-format deleted file mode 100644 index e7d00feaa08..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.clang-format +++ /dev/null @@ -1,5 +0,0 @@ ---- -Language: Cpp -BasedOnStyle: Google -PointerAlignment: Left -... diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.gitignore b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.gitignore deleted file mode 100644 index 806d04c6b3e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.gitignore +++ /dev/null @@ -1,61 +0,0 @@ -*.a -*.so -*.so.?* -*.dll -*.exe -*.dylib -*.cmake -!/cmake/*.cmake -!/test/AssemblyTests.cmake -*~ -*.pyc -__pycache__ - -# lcov -*.lcov -/lcov - -# cmake files. -/Testing -CMakeCache.txt -CMakeFiles/ -cmake_install.cmake - -# makefiles. -Makefile - -# in-source build. -bin/ -lib/ -/test/*_test - -# exuberant ctags. -tags - -# YouCompleteMe configuration. -.ycm_extra_conf.pyc - -# ninja generated files. -.ninja_deps -.ninja_log -build.ninja -install_manifest.txt -rules.ninja - -# bazel output symlinks. -bazel-* - -# out-of-source build top-level folders. -build/ -_build/ -build*/ - -# in-source dependencies -/googletest/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -CMakeSettings.json - -# Visual Studio Code cache/options directory -.vscode/ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.travis-libcxx-setup.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.travis-libcxx-setup.sh deleted file mode 100644 index a591743c6a6..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.travis-libcxx-setup.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bash - -# Install a newer CMake version -curl -sSL https://cmake.org/files/v3.6/cmake-3.6.1-Linux-x86_64.sh -o install-cmake.sh -chmod +x install-cmake.sh -sudo ./install-cmake.sh --prefix=/usr/local --skip-license - -# Checkout LLVM sources -git clone --depth=1 https://github.com/llvm-mirror/llvm.git llvm-source -git clone --depth=1 https://github.com/llvm-mirror/libcxx.git llvm-source/projects/libcxx -git clone --depth=1 https://github.com/llvm-mirror/libcxxabi.git llvm-source/projects/libcxxabi - -# Setup libc++ options -if [ -z "$BUILD_32_BITS" ]; then - export BUILD_32_BITS=OFF && echo disabling 32 bit build -fi - -# Build and install libc++ (Use unstable ABI for better sanitizer coverage) -mkdir llvm-build && cd llvm-build -cmake -DCMAKE_C_COMPILER=${C_COMPILER} -DCMAKE_CXX_COMPILER=${COMPILER} \ - -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=/usr \ - -DLIBCXX_ABI_UNSTABLE=ON \ - -DLLVM_USE_SANITIZER=${LIBCXX_SANITIZER} \ - -DLLVM_BUILD_32_BITS=${BUILD_32_BITS} \ - ../llvm-source -make cxx -j2 -sudo make install-cxxabi install-cxx -cd ../ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.travis.yml b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.travis.yml deleted file mode 100644 index 6b6cfc70465..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.travis.yml +++ /dev/null @@ -1,235 +0,0 @@ -sudo: required -dist: trusty -language: cpp - -env: - global: - - /usr/local/bin:$PATH - -matrix: - include: - - compiler: gcc - addons: - apt: - packages: - - lcov - env: COMPILER=g++ C_COMPILER=gcc BUILD_TYPE=Coverage - - compiler: gcc - env: COMPILER=g++ C_COMPILER=gcc BUILD_TYPE=Debug - - compiler: gcc - env: COMPILER=g++ C_COMPILER=gcc BUILD_TYPE=Release - - compiler: gcc - addons: - apt: - packages: - - g++-multilib - - libc6:i386 - env: - - COMPILER=g++ - - C_COMPILER=gcc - - BUILD_TYPE=Debug - - BUILD_32_BITS=ON - - EXTRA_FLAGS="-m32" - - compiler: gcc - addons: - apt: - packages: - - g++-multilib - - libc6:i386 - env: - - COMPILER=g++ - - C_COMPILER=gcc - - BUILD_TYPE=Release - - BUILD_32_BITS=ON - - EXTRA_FLAGS="-m32" - - compiler: gcc - env: - - INSTALL_GCC6_FROM_PPA=1 - - COMPILER=g++-6 C_COMPILER=gcc-6 BUILD_TYPE=Debug - - ENABLE_SANITIZER=1 - - EXTRA_FLAGS="-fno-omit-frame-pointer -g -O2 -fsanitize=undefined,address -fuse-ld=gold" - - compiler: clang - env: COMPILER=clang++ C_COMPILER=clang BUILD_TYPE=Debug - - compiler: clang - env: COMPILER=clang++ C_COMPILER=clang BUILD_TYPE=Release - # Clang w/ libc++ - - compiler: clang - dist: xenial - addons: - apt: - packages: - clang-3.8 - env: - - INSTALL_GCC6_FROM_PPA=1 - - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug - - LIBCXX_BUILD=1 - - EXTRA_CXX_FLAGS="-stdlib=libc++" - - compiler: clang - dist: xenial - addons: - apt: - packages: - clang-3.8 - env: - - INSTALL_GCC6_FROM_PPA=1 - - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Release - - LIBCXX_BUILD=1 - - EXTRA_CXX_FLAGS="-stdlib=libc++" - # Clang w/ 32bit libc++ - - compiler: clang - dist: xenial - addons: - apt: - packages: - - clang-3.8 - - g++-multilib - - libc6:i386 - env: - - INSTALL_GCC6_FROM_PPA=1 - - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug - - LIBCXX_BUILD=1 - - BUILD_32_BITS=ON - - EXTRA_FLAGS="-m32" - - EXTRA_CXX_FLAGS="-stdlib=libc++" - # Clang w/ 32bit libc++ - - compiler: clang - dist: xenial - addons: - apt: - packages: - - clang-3.8 - - g++-multilib - - libc6:i386 - env: - - INSTALL_GCC6_FROM_PPA=1 - - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Release - - LIBCXX_BUILD=1 - - BUILD_32_BITS=ON - - EXTRA_FLAGS="-m32" - - EXTRA_CXX_FLAGS="-stdlib=libc++" - # Clang w/ libc++, ASAN, UBSAN - - compiler: clang - dist: xenial - addons: - apt: - packages: - clang-3.8 - env: - - INSTALL_GCC6_FROM_PPA=1 - - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug - - LIBCXX_BUILD=1 LIBCXX_SANITIZER="Undefined;Address" - - ENABLE_SANITIZER=1 - - EXTRA_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=undefined,address -fno-sanitize-recover=all" - - EXTRA_CXX_FLAGS="-stdlib=libc++" - - UBSAN_OPTIONS=print_stacktrace=1 - # Clang w/ libc++ and MSAN - - compiler: clang - dist: xenial - addons: - apt: - packages: - clang-3.8 - env: - - INSTALL_GCC6_FROM_PPA=1 - - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug - - LIBCXX_BUILD=1 LIBCXX_SANITIZER=MemoryWithOrigins - - ENABLE_SANITIZER=1 - - EXTRA_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=memory -fsanitize-memory-track-origins" - - EXTRA_CXX_FLAGS="-stdlib=libc++" - # Clang w/ libc++ and MSAN - - compiler: clang - dist: xenial - addons: - apt: - packages: - clang-3.8 - env: - - INSTALL_GCC6_FROM_PPA=1 - - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=RelWithDebInfo - - LIBCXX_BUILD=1 LIBCXX_SANITIZER=Thread - - ENABLE_SANITIZER=1 - - EXTRA_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=thread -fno-sanitize-recover=all" - - EXTRA_CXX_FLAGS="-stdlib=libc++" - - os: osx - osx_image: xcode8.3 - compiler: clang - env: - - COMPILER=clang++ BUILD_TYPE=Debug - - os: osx - osx_image: xcode8.3 - compiler: clang - env: - - COMPILER=clang++ BUILD_TYPE=Release - - os: osx - osx_image: xcode8.3 - compiler: clang - env: - - COMPILER=clang++ - - BUILD_TYPE=Release - - BUILD_32_BITS=ON - - EXTRA_FLAGS="-m32" - - os: osx - osx_image: xcode8.3 - compiler: gcc - env: - - COMPILER=g++-7 C_COMPILER=gcc-7 BUILD_TYPE=Debug - -before_script: - - if [ -n "${LIBCXX_BUILD}" ]; then - source .travis-libcxx-setup.sh; - fi - - if [ -n "${ENABLE_SANITIZER}" ]; then - export EXTRA_OPTIONS="-DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF"; - else - export EXTRA_OPTIONS=""; - fi - - mkdir -p build && cd build - -before_install: - - if [ -z "$BUILD_32_BITS" ]; then - export BUILD_32_BITS=OFF && echo disabling 32 bit build; - fi - - if [ -n "${INSTALL_GCC6_FROM_PPA}" ]; then - sudo add-apt-repository -y "ppa:ubuntu-toolchain-r/test"; - sudo apt-get update --option Acquire::Retries=100 --option Acquire::http::Timeout="60"; - fi - -install: - - if [ -n "${INSTALL_GCC6_FROM_PPA}" ]; then - travis_wait sudo -E apt-get -yq --no-install-suggests --no-install-recommends install g++-6; - fi - - if [ "${TRAVIS_OS_NAME}" == "linux" -a "${BUILD_32_BITS}" == "OFF" ]; then - travis_wait sudo -E apt-get -y --no-install-suggests --no-install-recommends install llvm-3.9-tools; - sudo cp /usr/lib/llvm-3.9/bin/FileCheck /usr/local/bin/; - fi - - if [ "${BUILD_TYPE}" == "Coverage" -a "${TRAVIS_OS_NAME}" == "linux" ]; then - PATH=~/.local/bin:${PATH}; - pip install --user --upgrade pip; - travis_wait pip install --user cpp-coveralls; - fi - - if [ "${C_COMPILER}" == "gcc-7" -a "${TRAVIS_OS_NAME}" == "osx" ]; then - rm -f /usr/local/include/c++; - brew update; - travis_wait brew install gcc@7; - fi - - if [ "${TRAVIS_OS_NAME}" == "linux" ]; then - sudo apt-get update -qq; - sudo apt-get install -qq unzip cmake3; - wget https://github.com/bazelbuild/bazel/releases/download/0.10.1/bazel-0.10.1-installer-linux-x86_64.sh --output-document bazel-installer.sh; - travis_wait sudo bash bazel-installer.sh; - fi - - if [ "${TRAVIS_OS_NAME}" == "osx" ]; then - curl -L -o bazel-installer.sh https://github.com/bazelbuild/bazel/releases/download/0.10.1/bazel-0.10.1-installer-darwin-x86_64.sh; - travis_wait sudo bash bazel-installer.sh; - fi - -script: - - cmake -DCMAKE_C_COMPILER=${C_COMPILER} -DCMAKE_CXX_COMPILER=${COMPILER} -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DCMAKE_C_FLAGS="${EXTRA_FLAGS}" -DCMAKE_CXX_FLAGS="${EXTRA_FLAGS} ${EXTRA_CXX_FLAGS}" -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON -DBENCHMARK_BUILD_32_BITS=${BUILD_32_BITS} ${EXTRA_OPTIONS} .. - - make - - ctest -C ${BUILD_TYPE} --output-on-failure - - bazel test -c dbg --define google_benchmark.have_regex=posix --announce_rc --verbose_failures --test_output=errors --keep_going //test/... - -after_success: - - if [ "${BUILD_TYPE}" == "Coverage" -a "${TRAVIS_OS_NAME}" == "linux" ]; then - coveralls --include src --include include --gcov-options '\-lp' --root .. --build-root .; - fi diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.ycm_extra_conf.py b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.ycm_extra_conf.py deleted file mode 100644 index 5649ddcc749..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/.ycm_extra_conf.py +++ /dev/null @@ -1,115 +0,0 @@ -import os -import ycm_core - -# These are the compilation flags that will be used in case there's no -# compilation database set (by default, one is not set). -# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR. -flags = [ -'-Wall', -'-Werror', -'-pedantic-errors', -'-std=c++0x', -'-fno-strict-aliasing', -'-O3', -'-DNDEBUG', -# ...and the same thing goes for the magic -x option which specifies the -# language that the files to be compiled are written in. This is mostly -# relevant for c++ headers. -# For a C project, you would set this to 'c' instead of 'c++'. -'-x', 'c++', -'-I', 'include', -'-isystem', '/usr/include', -'-isystem', '/usr/local/include', -] - - -# Set this to the absolute path to the folder (NOT the file!) containing the -# compile_commands.json file to use that instead of 'flags'. See here for -# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html -# -# Most projects will NOT need to set this to anything; you can just change the -# 'flags' list of compilation flags. Notice that YCM itself uses that approach. -compilation_database_folder = '' - -if os.path.exists( compilation_database_folder ): - database = ycm_core.CompilationDatabase( compilation_database_folder ) -else: - database = None - -SOURCE_EXTENSIONS = [ '.cc' ] - -def DirectoryOfThisScript(): - return os.path.dirname( os.path.abspath( __file__ ) ) - - -def MakeRelativePathsInFlagsAbsolute( flags, working_directory ): - if not working_directory: - return list( flags ) - new_flags = [] - make_next_absolute = False - path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ] - for flag in flags: - new_flag = flag - - if make_next_absolute: - make_next_absolute = False - if not flag.startswith( '/' ): - new_flag = os.path.join( working_directory, flag ) - - for path_flag in path_flags: - if flag == path_flag: - make_next_absolute = True - break - - if flag.startswith( path_flag ): - path = flag[ len( path_flag ): ] - new_flag = path_flag + os.path.join( working_directory, path ) - break - - if new_flag: - new_flags.append( new_flag ) - return new_flags - - -def IsHeaderFile( filename ): - extension = os.path.splitext( filename )[ 1 ] - return extension in [ '.h', '.hxx', '.hpp', '.hh' ] - - -def GetCompilationInfoForFile( filename ): - # The compilation_commands.json file generated by CMake does not have entries - # for header files. So we do our best by asking the db for flags for a - # corresponding source file, if any. If one exists, the flags for that file - # should be good enough. - if IsHeaderFile( filename ): - basename = os.path.splitext( filename )[ 0 ] - for extension in SOURCE_EXTENSIONS: - replacement_file = basename + extension - if os.path.exists( replacement_file ): - compilation_info = database.GetCompilationInfoForFile( - replacement_file ) - if compilation_info.compiler_flags_: - return compilation_info - return None - return database.GetCompilationInfoForFile( filename ) - - -def FlagsForFile( filename, **kwargs ): - if database: - # Bear in mind that compilation_info.compiler_flags_ does NOT return a - # python list, but a "list-like" StringVec object - compilation_info = GetCompilationInfoForFile( filename ) - if not compilation_info: - return None - - final_flags = MakeRelativePathsInFlagsAbsolute( - compilation_info.compiler_flags_, - compilation_info.compiler_working_dir_ ) - else: - relative_to = DirectoryOfThisScript() - final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to ) - - return { - 'flags': final_flags, - 'do_cache': True - } diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/AUTHORS b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/AUTHORS deleted file mode 100644 index 912cbbc13cf..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/AUTHORS +++ /dev/null @@ -1,51 +0,0 @@ -# This is the official list of benchmark authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. -# -# Names should be added to this file as: -# Name or Organization -# The email address is not required for organizations. -# -# Please keep the list sorted. - -Albert Pretorius -Alex Steele -Andriy Berestovskyy -Arne Beer -Carto -Christopher Seymour -Daniel Harvey -David Coeurjolly -Deniz Evrenci -Dirac Research -Dominik Czarnota -Eric Fiselier -Eugene Zhuk -Evgeny Safronov -Federico Ficarelli -Felix Homann -Google Inc. -International Business Machines Corporation -Ismael Jimenez Martinez -Jern-Kuan Leong -JianXiong Zhou -Joao Paulo Magalhaes -Jussi Knuuttila -Kaito Udagawa -Kishan Kumar -Lei Xu -Matt Clarkson -Maxim Vafin -MongoDB Inc. -Nick Hutchinson -Oleksandr Sochka -Ori Livneh -Paul Redmond -Radoslav Yovchev -Roman Lebedev -Shuo Chen -Steinar H. Gunderson -Stripe, Inc. -Yixuan Qiu -Yusuke Suzuki -Zbigniew Skowron diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/BUILD.bazel b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/BUILD.bazel deleted file mode 100644 index 6ee69f29072..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/BUILD.bazel +++ /dev/null @@ -1,42 +0,0 @@ -licenses(["notice"]) - -config_setting( - name = "windows", - values = { - "cpu": "x64_windows", - }, - visibility = [":__subpackages__"], -) - -cc_library( - name = "benchmark", - srcs = glob( - [ - "src/*.cc", - "src/*.h", - ], - exclude = ["src/benchmark_main.cc"], - ), - hdrs = ["include/benchmark/benchmark.h"], - linkopts = select({ - ":windows": ["-DEFAULTLIB:shlwapi.lib"], - "//conditions:default": ["-pthread"], - }), - strip_include_prefix = "include", - visibility = ["//visibility:public"], -) - -cc_library( - name = "benchmark_main", - srcs = ["src/benchmark_main.cc"], - hdrs = ["include/benchmark/benchmark.h"], - strip_include_prefix = "include", - visibility = ["//visibility:public"], - deps = [":benchmark"], -) - -cc_library( - name = "benchmark_internal_headers", - hdrs = glob(["src/*.h"]), - visibility = ["//test:__pkg__"], -) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/CMakeLists.txt b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/CMakeLists.txt deleted file mode 100644 index 9db1361212d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/CMakeLists.txt +++ /dev/null @@ -1,276 +0,0 @@ -cmake_minimum_required (VERSION 3.5.1) - -foreach(p - CMP0048 # OK to clear PROJECT_VERSION on project() - CMP0054 # CMake 3.1 - CMP0056 # export EXE_LINKER_FLAGS to try_run - CMP0057 # Support no if() IN_LIST operator - CMP0063 # Honor visibility properties for all targets - ) - if(POLICY ${p}) - cmake_policy(SET ${p} NEW) - endif() -endforeach() - -project (benchmark CXX) - -option(BENCHMARK_ENABLE_TESTING "Enable testing of the benchmark library." ON) -option(BENCHMARK_ENABLE_EXCEPTIONS "Enable the use of exceptions in the benchmark library." ON) -option(BENCHMARK_ENABLE_LTO "Enable link time optimisation of the benchmark library." OFF) -option(BENCHMARK_USE_LIBCXX "Build and test using libc++ as the standard library." OFF) -if(NOT MSVC) - option(BENCHMARK_BUILD_32_BITS "Build a 32 bit version of the library." OFF) -else() - set(BENCHMARK_BUILD_32_BITS OFF CACHE BOOL "Build a 32 bit version of the library - unsupported when using MSVC)" FORCE) -endif() -option(BENCHMARK_ENABLE_INSTALL "Enable installation of benchmark. (Projects embedding benchmark may want to turn this OFF.)" ON) - -# Allow unmet dependencies to be met using CMake's ExternalProject mechanics, which -# may require downloading the source code. -option(BENCHMARK_DOWNLOAD_DEPENDENCIES "Allow the downloading and in-tree building of unmet dependencies" OFF) - -# This option can be used to disable building and running unit tests which depend on gtest -# in cases where it is not possible to build or find a valid version of gtest. -option(BENCHMARK_ENABLE_GTEST_TESTS "Enable building the unit tests which depend on gtest" ON) - -set(ENABLE_ASSEMBLY_TESTS_DEFAULT OFF) -function(should_enable_assembly_tests) - if(CMAKE_BUILD_TYPE) - string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER) - if (${CMAKE_BUILD_TYPE_LOWER} MATCHES "coverage") - # FIXME: The --coverage flag needs to be removed when building assembly - # tests for this to work. - return() - endif() - endif() - if (MSVC) - return() - elseif(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64") - return() - elseif(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) - # FIXME: Make these work on 32 bit builds - return() - elseif(BENCHMARK_BUILD_32_BITS) - # FIXME: Make these work on 32 bit builds - return() - endif() - find_program(LLVM_FILECHECK_EXE FileCheck) - if (LLVM_FILECHECK_EXE) - set(LLVM_FILECHECK_EXE "${LLVM_FILECHECK_EXE}" CACHE PATH "llvm filecheck" FORCE) - message(STATUS "LLVM FileCheck Found: ${LLVM_FILECHECK_EXE}") - else() - message(STATUS "Failed to find LLVM FileCheck") - return() - endif() - set(ENABLE_ASSEMBLY_TESTS_DEFAULT ON PARENT_SCOPE) -endfunction() -should_enable_assembly_tests() - -# This option disables the building and running of the assembly verification tests -option(BENCHMARK_ENABLE_ASSEMBLY_TESTS "Enable building and running the assembly tests" - ${ENABLE_ASSEMBLY_TESTS_DEFAULT}) - -# Make sure we can import out CMake functions -list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules") -list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") - - -# Read the git tags to determine the project version -include(GetGitVersion) -get_git_version(GIT_VERSION) - -# Tell the user what versions we are using -string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" VERSION ${GIT_VERSION}) -message(STATUS "Version: ${VERSION}") - -# The version of the libraries -set(GENERIC_LIB_VERSION ${VERSION}) -string(SUBSTRING ${VERSION} 0 1 GENERIC_LIB_SOVERSION) - -# Import our CMake modules -include(CheckCXXCompilerFlag) -include(AddCXXCompilerFlag) -include(CXXFeatureCheck) - -if (BENCHMARK_BUILD_32_BITS) - add_required_cxx_compiler_flag(-m32) -endif() - -if (MSVC) - # Turn compiler warnings up to 11 - string(REGEX REPLACE "[-/]W[1-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4") - add_definitions(-D_CRT_SECURE_NO_WARNINGS) - - if (NOT BENCHMARK_ENABLE_EXCEPTIONS) - add_cxx_compiler_flag(-EHs-) - add_cxx_compiler_flag(-EHa-) - add_definitions(-D_HAS_EXCEPTIONS=0) - endif() - # Link time optimisation - if (BENCHMARK_ENABLE_LTO) - set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /GL") - set(CMAKE_STATIC_LINKER_FLAGS_RELEASE "${CMAKE_STATIC_LINKER_FLAGS_RELEASE} /LTCG") - set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /LTCG") - set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /LTCG") - - set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /GL") - string(REGEX REPLACE "[-/]INCREMENTAL" "/INCREMENTAL:NO" CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO}") - set(CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") - string(REGEX REPLACE "[-/]INCREMENTAL" "/INCREMENTAL:NO" CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO}") - set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") - string(REGEX REPLACE "[-/]INCREMENTAL" "/INCREMENTAL:NO" CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO}") - set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") - - set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /GL") - set(CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL "${CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL} /LTCG") - set(CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL "${CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL} /LTCG") - set(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL "${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL} /LTCG") - endif() -else() - # Try and enable C++11. Don't use C++14 because it doesn't work in some - # configurations. - add_cxx_compiler_flag(-std=c++11) - if (NOT HAVE_CXX_FLAG_STD_CXX11) - add_cxx_compiler_flag(-std=c++0x) - endif() - - # Turn compiler warnings up to 11 - add_cxx_compiler_flag(-Wall) - add_cxx_compiler_flag(-Wextra) - add_cxx_compiler_flag(-Wshadow) - add_cxx_compiler_flag(-Werror RELEASE) - add_cxx_compiler_flag(-Werror RELWITHDEBINFO) - add_cxx_compiler_flag(-Werror MINSIZEREL) - add_cxx_compiler_flag(-pedantic) - add_cxx_compiler_flag(-pedantic-errors) - add_cxx_compiler_flag(-Wshorten-64-to-32) - add_cxx_compiler_flag(-fstrict-aliasing) - # Disable warnings regarding deprecated parts of the library while building - # and testing those parts of the library. - add_cxx_compiler_flag(-Wno-deprecated-declarations) - if (CMAKE_CXX_COMPILER_ID STREQUAL "Intel") - # Intel silently ignores '-Wno-deprecated-declarations', - # warning no. 1786 must be explicitly disabled. - # See #631 for rationale. - add_cxx_compiler_flag(-wd1786) - endif() - # Disable deprecation warnings for release builds (when -Werror is enabled). - add_cxx_compiler_flag(-Wno-deprecated RELEASE) - add_cxx_compiler_flag(-Wno-deprecated RELWITHDEBINFO) - add_cxx_compiler_flag(-Wno-deprecated MINSIZEREL) - if (NOT BENCHMARK_ENABLE_EXCEPTIONS) - add_cxx_compiler_flag(-fno-exceptions) - endif() - - if (HAVE_CXX_FLAG_FSTRICT_ALIASING) - if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "Intel") #ICC17u2: Many false positives for Wstrict-aliasing - add_cxx_compiler_flag(-Wstrict-aliasing) - endif() - endif() - # ICC17u2: overloaded virtual function "benchmark::Fixture::SetUp" is only partially overridden - # (because of deprecated overload) - add_cxx_compiler_flag(-wd654) - add_cxx_compiler_flag(-Wthread-safety) - if (HAVE_CXX_FLAG_WTHREAD_SAFETY) - cxx_feature_check(THREAD_SAFETY_ATTRIBUTES) - endif() - - # On most UNIX like platforms g++ and clang++ define _GNU_SOURCE as a - # predefined macro, which turns on all of the wonderful libc extensions. - # However g++ doesn't do this in Cygwin so we have to define it ourselfs - # since we depend on GNU/POSIX/BSD extensions. - if (CYGWIN) - add_definitions(-D_GNU_SOURCE=1) - endif() - - if (QNXNTO) - add_definitions(-D_QNX_SOURCE) - endif() - - # Link time optimisation - if (BENCHMARK_ENABLE_LTO) - add_cxx_compiler_flag(-flto) - if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - find_program(GCC_AR gcc-ar) - if (GCC_AR) - set(CMAKE_AR ${GCC_AR}) - endif() - find_program(GCC_RANLIB gcc-ranlib) - if (GCC_RANLIB) - set(CMAKE_RANLIB ${GCC_RANLIB}) - endif() - elseif("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") - include(llvm-toolchain) - endif() - endif() - - # Coverage build type - set(BENCHMARK_CXX_FLAGS_COVERAGE "${CMAKE_CXX_FLAGS_DEBUG}" - CACHE STRING "Flags used by the C++ compiler during coverage builds." - FORCE) - set(BENCHMARK_EXE_LINKER_FLAGS_COVERAGE "${CMAKE_EXE_LINKER_FLAGS_DEBUG}" - CACHE STRING "Flags used for linking binaries during coverage builds." - FORCE) - set(BENCHMARK_SHARED_LINKER_FLAGS_COVERAGE "${CMAKE_SHARED_LINKER_FLAGS_DEBUG}" - CACHE STRING "Flags used by the shared libraries linker during coverage builds." - FORCE) - mark_as_advanced( - BENCHMARK_CXX_FLAGS_COVERAGE - BENCHMARK_EXE_LINKER_FLAGS_COVERAGE - BENCHMARK_SHARED_LINKER_FLAGS_COVERAGE) - set(CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" CACHE STRING - "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel Coverage.") - add_cxx_compiler_flag(--coverage COVERAGE) -endif() - -if (BENCHMARK_USE_LIBCXX) - if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") - add_cxx_compiler_flag(-stdlib=libc++) - elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR - "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel") - add_cxx_compiler_flag(-nostdinc++) - message(WARNING "libc++ header path must be manually specified using CMAKE_CXX_FLAGS") - # Adding -nodefaultlibs directly to CMAKE__LINKER_FLAGS will break - # configuration checks such as 'find_package(Threads)' - list(APPEND BENCHMARK_CXX_LINKER_FLAGS -nodefaultlibs) - # -lc++ cannot be added directly to CMAKE__LINKER_FLAGS because - # linker flags appear before all linker inputs and -lc++ must appear after. - list(APPEND BENCHMARK_CXX_LIBRARIES c++) - else() - message(FATAL_ERROR "-DBENCHMARK_USE_LIBCXX:BOOL=ON is not supported for compiler") - endif() -endif(BENCHMARK_USE_LIBCXX) - -# C++ feature checks -# Determine the correct regular expression engine to use -cxx_feature_check(STD_REGEX) -cxx_feature_check(GNU_POSIX_REGEX) -cxx_feature_check(POSIX_REGEX) -if(NOT HAVE_STD_REGEX AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX) - message(FATAL_ERROR "Failed to determine the source files for the regular expression backend") -endif() -if (NOT BENCHMARK_ENABLE_EXCEPTIONS AND HAVE_STD_REGEX - AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX) - message(WARNING "Using std::regex with exceptions disabled is not fully supported") -endif() -cxx_feature_check(STEADY_CLOCK) -# Ensure we have pthreads -set(THREADS_PREFER_PTHREAD_FLAG ON) -find_package(Threads REQUIRED) - -# Set up directories -include_directories(${PROJECT_SOURCE_DIR}/include) - -# Build the targets -add_subdirectory(src) - -if (BENCHMARK_ENABLE_TESTING) - enable_testing() - if (BENCHMARK_ENABLE_GTEST_TESTS AND - NOT (TARGET gtest AND TARGET gtest_main AND - TARGET gmock AND TARGET gmock_main)) - include(GoogleTest) - endif() - add_subdirectory(test) -endif() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/CONTRIBUTING.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/CONTRIBUTING.md deleted file mode 100644 index 43de4c9d470..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/CONTRIBUTING.md +++ /dev/null @@ -1,58 +0,0 @@ -# How to contribute # - -We'd love to accept your patches and contributions to this project. There are -a just a few small guidelines you need to follow. - - -## Contributor License Agreement ## - -Contributions to any Google project must be accompanied by a Contributor -License Agreement. This is not a copyright **assignment**, it simply gives -Google permission to use and redistribute your contributions as part of the -project. - - * If you are an individual writing original source code and you're sure you - own the intellectual property, then you'll need to sign an [individual - CLA][]. - - * If you work for a company that wants to allow you to contribute your work, - then you'll need to sign a [corporate CLA][]. - -You generally only need to submit a CLA once, so if you've already submitted -one (even if it was for a different project), you probably don't need to do it -again. - -[individual CLA]: https://developers.google.com/open-source/cla/individual -[corporate CLA]: https://developers.google.com/open-source/cla/corporate - -Once your CLA is submitted (or if you already submitted one for -another Google project), make a commit adding yourself to the -[AUTHORS][] and [CONTRIBUTORS][] files. This commit can be part -of your first [pull request][]. - -[AUTHORS]: AUTHORS -[CONTRIBUTORS]: CONTRIBUTORS - - -## Submitting a patch ## - - 1. It's generally best to start by opening a new issue describing the bug or - feature you're intending to fix. Even if you think it's relatively minor, - it's helpful to know what people are working on. Mention in the initial - issue that you are planning to work on that bug or feature so that it can - be assigned to you. - - 1. Follow the normal process of [forking][] the project, and setup a new - branch to work in. It's important that each group of changes be done in - separate branches in order to ensure that a pull request only includes the - commits related to that bug or feature. - - 1. Do your best to have [well-formed commit messages][] for each change. - This provides consistency throughout the project, and ensures that commit - messages are able to be formatted properly by various git tools. - - 1. Finally, push the commits to your fork and submit a [pull request][]. - -[forking]: https://help.github.com/articles/fork-a-repo -[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html -[pull request]: https://help.github.com/articles/creating-a-pull-request diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/CONTRIBUTORS b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/CONTRIBUTORS deleted file mode 100644 index b680efc8c4a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/CONTRIBUTORS +++ /dev/null @@ -1,72 +0,0 @@ -# People who have agreed to one of the CLAs and can contribute patches. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# https://developers.google.com/open-source/cla/individual -# https://developers.google.com/open-source/cla/corporate -# -# The agreement for individuals can be filled out on the web. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. -# -# Names should be added to this file as: -# Name -# -# Please keep the list sorted. - -Albert Pretorius -Alex Steele -Andriy Berestovskyy -Arne Beer -Billy Robert O'Neal III -Chris Kennelly -Christopher Seymour -Cyrille Faucheux -Daniel Harvey -David Coeurjolly -Deniz Evrenci -Dominic Hamon -Dominik Czarnota -Eric Fiselier -Eugene Zhuk -Evgeny Safronov -Federico Ficarelli -Felix Homann -Hannes Hauswedell -Ismael Jimenez Martinez -Jern-Kuan Leong -JianXiong Zhou -Joao Paulo Magalhaes -John Millikin -Jussi Knuuttila -Kai Wolf -Kishan Kumar -Kaito Udagawa -Lei Xu -Matt Clarkson -Maxim Vafin -Nick Hutchinson -Oleksandr Sochka -Ori Livneh -Pascal Leroy -Paul Redmond -Pierre Phaneuf -Radoslav Yovchev -Raul Marin -Ray Glover -Robert Guo -Roman Lebedev -Shuo Chen -Tobias Ulvgård -Tom Madams -Yixuan Qiu -Yusuke Suzuki -Zbigniew Skowron diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/LICENSE b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/LICENSE deleted file mode 100644 index d6456956733..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/README.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/README.md deleted file mode 100644 index 45e41588438..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/README.md +++ /dev/null @@ -1,1179 +0,0 @@ -# Benchmark -[![Build Status](https://travis-ci.org/google/benchmark.svg?branch=master)](https://travis-ci.org/google/benchmark) -[![Build status](https://ci.appveyor.com/api/projects/status/u0qsyp7t1tk7cpxs/branch/master?svg=true)](https://ci.appveyor.com/project/google/benchmark/branch/master) -[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark) -[![slackin](https://slackin-iqtfqnpzxd.now.sh/badge.svg)](https://slackin-iqtfqnpzxd.now.sh/) - - -A library to benchmark code snippets, similar to unit tests. Example: - -```c++ -#include - -static void BM_SomeFunction(benchmark::State& state) { - // Perform setup here - for (auto _ : state) { - // This code gets timed - SomeFunction(); - } -} -// Register the function as a benchmark -BENCHMARK(BM_SomeFunction); -// Run the benchmark -BENCHMARK_MAIN(); -``` - -To get started, see [Requirements](#requirements) and -[Installation](#installation). See [Usage](#usage) for a full example and the -[User Guide](#user-guide) for a more comprehensive feature overview. - -It may also help to read the [Google Test documentation](https://github.com/google/googletest/blob/master/googletest/docs/primer.md) -as some of the structural aspects of the APIs are similar. - -### Resources - -[Discussion group](https://groups.google.com/d/forum/benchmark-discuss) - -IRC channel: [freenode](https://freenode.net) #googlebenchmark - -[Additional Tooling Documentation](docs/tools.md) - -[Assembly Testing Documentation](docs/AssemblyTests.md) - -## Requirements - -The library can be used with C++03. However, it requires C++11 to build, -including compiler and standard library support. - -The following minimum versions are required to build the library: - -* GCC 4.8 -* Clang 3.4 -* Visual Studio 2013 -* Intel 2015 Update 1 - -## Installation - -This describes the installation process using cmake. As pre-requisites, you'll -need git and cmake installed. - -_See [dependencies.md](dependencies.md) for more details regarding supported -versions of build tools._ - -```bash -# Check out the library. -$ git clone https://github.com/google/benchmark.git -# Benchmark requires Google Test as a dependency. Add the source tree as a subdirectory. -$ git clone https://github.com/google/googletest.git benchmark/googletest -# Make a build directory to place the build output. -$ mkdir build && cd build -# Generate a Makefile with cmake. -# Use cmake -G to generate a different file type. -$ cmake ../benchmark -# Build the library. -$ make -``` -This builds the `benchmark` and `benchmark_main` libraries and tests. -On a unix system, the build directory should now look something like this: - -``` -/benchmark -/build - /src - /libbenchmark.a - /libbenchmark_main.a - /test - ... -``` - -Next, you can run the tests to check the build. - -```bash -$ make test -``` - -If you want to install the library globally, also run: - -``` -sudo make install -``` - -Note that Google Benchmark requires Google Test to build and run the tests. This -dependency can be provided two ways: - -* Checkout the Google Test sources into `benchmark/googletest` as above. -* Otherwise, if `-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON` is specified during - configuration, the library will automatically download and build any required - dependencies. - -If you do not wish to build and run the tests, add `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF` -to `CMAKE_ARGS`. - -### Debug vs Release - -By default, benchmark builds as a debug library. You will see a warning in the -output when this is the case. To build it as a release library instead, use: - -``` -cmake -DCMAKE_BUILD_TYPE=Release -``` - -To enable link-time optimisation, use - -``` -cmake -DCMAKE_BUILD_TYPE=Release -DBENCHMARK_ENABLE_LTO=true -``` - -If you are using gcc, you might need to set `GCC_AR` and `GCC_RANLIB` cmake -cache variables, if autodetection fails. - -If you are using clang, you may need to set `LLVMAR_EXECUTABLE`, -`LLVMNM_EXECUTABLE` and `LLVMRANLIB_EXECUTABLE` cmake cache variables. - - -### Stable and Experimental Library Versions - -The main branch contains the latest stable version of the benchmarking library; -the API of which can be considered largely stable, with source breaking changes -being made only upon the release of a new major version. - -Newer, experimental, features are implemented and tested on the -[`v2` branch](https://github.com/google/benchmark/tree/v2). Users who wish -to use, test, and provide feedback on the new features are encouraged to try -this branch. However, this branch provides no stability guarantees and reserves -the right to change and break the API at any time. - -## Usage -### Basic usage -Define a function that executes the code to measure, register it as a benchmark -function using the `BENCHMARK` macro, and ensure an appropriate `main` function -is available: - -```c++ -#include - -static void BM_StringCreation(benchmark::State& state) { - for (auto _ : state) - std::string empty_string; -} -// Register the function as a benchmark -BENCHMARK(BM_StringCreation); - -// Define another benchmark -static void BM_StringCopy(benchmark::State& state) { - std::string x = "hello"; - for (auto _ : state) - std::string copy(x); -} -BENCHMARK(BM_StringCopy); - -BENCHMARK_MAIN(); -``` - -To run the benchmark, compile and link against the `benchmark` library -(libbenchmark.a/.so). If you followed the build steps above, this -library will be under the build directory you created. - -```bash -# Example on linux after running the build steps above. Assumes the -# `benchmark` and `build` directories are under the current directory. -$ g++ -std=c++11 -isystem benchmark/include -Lbuild/src -lpthread \ - -lbenchmark mybenchmark.cc -o mybenchmark -``` - -Alternatively, link against the `benchmark_main` library and remove -`BENCHMARK_MAIN();` above to get the same behavior. - -The compiled executable will run all benchmarks by default. Pass the `--help` -flag for option information or see the guide below. - -### Platform-specific instructions - -When the library is built using GCC it is necessary to link with the pthread -library due to how GCC implements `std::thread`. Failing to link to pthread will -lead to runtime exceptions (unless you're using libc++), not linker errors. See -[issue #67](https://github.com/google/benchmark/issues/67) for more details. You -can link to pthread by adding `-pthread` to your linker command. Note, you can -also use `-lpthread`, but there are potential issues with ordering of command -line parameters if you use that. - -If you're running benchmarks on Windows, the shlwapi library (`-lshlwapi`) is -also required. - -If you're running benchmarks on solaris, you'll want the kstat library linked in -too (`-lkstat`). - -## User Guide - -### Command Line -[Output Formats](#output-formats) - -[Output Files](#output-files) - -[Running a Subset of Benchmarks](#running-a-subset-of-benchmarks) - -[Result Comparison](#result-comparison) - -### Library -[Runtime and Reporting Considerations](#runtime-and-reporting-considerations) - -[Passing Arguments](#passing-arguments) - -[Calculating Asymptotic Complexity](#asymptotic-complexity) - -[Templated Benchmarks](#templated-benchmarks) - -[Fixtures](#fixtures) - -[Custom Counters](#custom-counters) - -[Multithreaded Benchmarks](#multithreaded-benchmarks) - -[CPU Timers](#cpu-timers) - -[Manual Timing](#manual-timing) - -[Setting the Time Unit](#setting-the-time-unit) - -[Preventing Optimization](#preventing-optimization) - -[Reporting Statistics](#reporting-statistics) - -[Custom Statistics](#custom-statistics) - -[Using RegisterBenchmark](#using-register-benchmark) - -[Exiting with an Error](#exiting-with-an-error) - -[A Faster KeepRunning Loop](#a-faster-keep-running-loop) - -[Disabling CPU Frequency Scaling](#disabling-cpu-frequency-scaling) - - - -### Output Formats - -The library supports multiple output formats. Use the -`--benchmark_format=` flag to set the format type. `console` -is the default format. - -The Console format is intended to be a human readable format. By default -the format generates color output. Context is output on stderr and the -tabular data on stdout. Example tabular output looks like: -``` -Benchmark Time(ns) CPU(ns) Iterations ----------------------------------------------------------------------- -BM_SetInsert/1024/1 28928 29349 23853 133.097kB/s 33.2742k items/s -BM_SetInsert/1024/8 32065 32913 21375 949.487kB/s 237.372k items/s -BM_SetInsert/1024/10 33157 33648 21431 1.13369MB/s 290.225k items/s -``` - -The JSON format outputs human readable json split into two top level attributes. -The `context` attribute contains information about the run in general, including -information about the CPU and the date. -The `benchmarks` attribute contains a list of every benchmark run. Example json -output looks like: -```json -{ - "context": { - "date": "2015/03/17-18:40:25", - "num_cpus": 40, - "mhz_per_cpu": 2801, - "cpu_scaling_enabled": false, - "build_type": "debug" - }, - "benchmarks": [ - { - "name": "BM_SetInsert/1024/1", - "iterations": 94877, - "real_time": 29275, - "cpu_time": 29836, - "bytes_per_second": 134066, - "items_per_second": 33516 - }, - { - "name": "BM_SetInsert/1024/8", - "iterations": 21609, - "real_time": 32317, - "cpu_time": 32429, - "bytes_per_second": 986770, - "items_per_second": 246693 - }, - { - "name": "BM_SetInsert/1024/10", - "iterations": 21393, - "real_time": 32724, - "cpu_time": 33355, - "bytes_per_second": 1199226, - "items_per_second": 299807 - } - ] -} -``` - -The CSV format outputs comma-separated values. The `context` is output on stderr -and the CSV itself on stdout. Example CSV output looks like: -``` -name,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label -"BM_SetInsert/1024/1",65465,17890.7,8407.45,475768,118942, -"BM_SetInsert/1024/8",116606,18810.1,9766.64,3.27646e+06,819115, -"BM_SetInsert/1024/10",106365,17238.4,8421.53,4.74973e+06,1.18743e+06, -``` - - - -### Output Files - -Write benchmark results to a file with the `--benchmark_out=` option. -Specify the output format with `--benchmark_out_format={json|console|csv}`. Note that Specifying -`--benchmark_out` does not suppress the console output. - - - -### Running a Subset of Benchmarks - -The `--benchmark_filter=` option can be used to only run the benchmarks -which match the specified ``. For example: - -```bash -$ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32 -Run on (1 X 2300 MHz CPU ) -2016-06-25 19:34:24 -Benchmark Time CPU Iterations ----------------------------------------------------- -BM_memcpy/32 11 ns 11 ns 79545455 -BM_memcpy/32k 2181 ns 2185 ns 324074 -BM_memcpy/32 12 ns 12 ns 54687500 -BM_memcpy/32k 1834 ns 1837 ns 357143 -``` - - - -### Result comparison - -It is possible to compare the benchmarking results. See [Additional Tooling Documentation](docs/tools.md) - - - -### Runtime and Reporting Considerations - -When the benchmark binary is executed, each benchmark function is run serially. -The number of iterations to run is determined dynamically by running the -benchmark a few times and measuring the time taken and ensuring that the -ultimate result will be statistically stable. As such, faster benchmark -functions will be run for more iterations than slower benchmark functions, and -the number of iterations is thus reported. - -In all cases, the number of iterations for which the benchmark is run is -governed by the amount of time the benchmark takes. Concretely, the number of -iterations is at least one, not more than 1e9, until CPU time is greater than -the minimum time, or the wallclock time is 5x minimum time. The minimum time is -set per benchmark by calling `MinTime` on the registered benchmark object. - -Average timings are then reported over the iterations run. If multiple -repetitions are requested using the `--benchmark_repetitions` command-line -option, or at registration time, the benchmark function will be run several -times and statistical results across these repetitions will also be reported. - -As well as the per-benchmark entries, a preamble in the report will include -information about the machine on which the benchmarks are run. - - - -### Passing Arguments - -Sometimes a family of benchmarks can be implemented with just one routine that -takes an extra argument to specify which one of the family of benchmarks to -run. For example, the following code defines a family of benchmarks for -measuring the speed of `memcpy()` calls of different lengths: - -```c++ -static void BM_memcpy(benchmark::State& state) { - char* src = new char[state.range(0)]; - char* dst = new char[state.range(0)]; - memset(src, 'x', state.range(0)); - for (auto _ : state) - memcpy(dst, src, state.range(0)); - state.SetBytesProcessed(int64_t(state.iterations()) * - int64_t(state.range(0))); - delete[] src; - delete[] dst; -} -BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10); -``` - -The preceding code is quite repetitive, and can be replaced with the following -short-hand. The following invocation will pick a few appropriate arguments in -the specified range and will generate a benchmark for each such argument. - -```c++ -BENCHMARK(BM_memcpy)->Range(8, 8<<10); -``` - -By default the arguments in the range are generated in multiples of eight and -the command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the -range multiplier is changed to multiples of two. - -```c++ -BENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10); -``` -Now arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ]. - -You might have a benchmark that depends on two or more inputs. For example, the -following code defines a family of benchmarks for measuring the speed of set -insertion. - -```c++ -static void BM_SetInsert(benchmark::State& state) { - std::set data; - for (auto _ : state) { - state.PauseTiming(); - data = ConstructRandomSet(state.range(0)); - state.ResumeTiming(); - for (int j = 0; j < state.range(1); ++j) - data.insert(RandomNumber()); - } -} -BENCHMARK(BM_SetInsert) - ->Args({1<<10, 128}) - ->Args({2<<10, 128}) - ->Args({4<<10, 128}) - ->Args({8<<10, 128}) - ->Args({1<<10, 512}) - ->Args({2<<10, 512}) - ->Args({4<<10, 512}) - ->Args({8<<10, 512}); -``` - -The preceding code is quite repetitive, and can be replaced with the following -short-hand. The following macro will pick a few appropriate arguments in the -product of the two specified ranges and will generate a benchmark for each such -pair. - -```c++ -BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}}); -``` - -For more complex patterns of inputs, passing a custom function to `Apply` allows -programmatic specification of an arbitrary set of arguments on which to run the -benchmark. The following example enumerates a dense range on one parameter, -and a sparse range on the second. - -```c++ -static void CustomArguments(benchmark::internal::Benchmark* b) { - for (int i = 0; i <= 10; ++i) - for (int j = 32; j <= 1024*1024; j *= 8) - b->Args({i, j}); -} -BENCHMARK(BM_SetInsert)->Apply(CustomArguments); -``` - -#### Passing Arbitrary Arguments to a Benchmark - -In C++11 it is possible to define a benchmark that takes an arbitrary number -of extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)` -macro creates a benchmark that invokes `func` with the `benchmark::State` as -the first argument followed by the specified `args...`. -The `test_case_name` is appended to the name of the benchmark and -should describe the values passed. - -```c++ -template -void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) { - [...] -} -// Registers a benchmark named "BM_takes_args/int_string_test" that passes -// the specified values to `extra_args`. -BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc")); -``` -Note that elements of `...args` may refer to global variables. Users should -avoid modifying global state inside of a benchmark. - - - -### Calculating Asymptotic Complexity (Big O) - -Asymptotic complexity might be calculated for a family of benchmarks. The -following code will calculate the coefficient for the high-order term in the -running time and the normalized root-mean square error of string comparison. - -```c++ -static void BM_StringCompare(benchmark::State& state) { - std::string s1(state.range(0), '-'); - std::string s2(state.range(0), '-'); - for (auto _ : state) { - benchmark::DoNotOptimize(s1.compare(s2)); - } - state.SetComplexityN(state.range(0)); -} -BENCHMARK(BM_StringCompare) - ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN); -``` - -As shown in the following invocation, asymptotic complexity might also be -calculated automatically. - -```c++ -BENCHMARK(BM_StringCompare) - ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(); -``` - -The following code will specify asymptotic complexity with a lambda function, -that might be used to customize high-order term calculation. - -```c++ -BENCHMARK(BM_StringCompare)->RangeMultiplier(2) - ->Range(1<<10, 1<<18)->Complexity([](int64_t n)->double{return n; }); -``` - - - -### Templated Benchmarks - -This example produces and consumes messages of size `sizeof(v)` `range_x` -times. It also outputs throughput in the absence of multiprogramming. - -```c++ -template void BM_Sequential(benchmark::State& state) { - Q q; - typename Q::value_type v; - for (auto _ : state) { - for (int i = state.range(0); i--; ) - q.push(v); - for (int e = state.range(0); e--; ) - q.Wait(&v); - } - // actually messages, not bytes: - state.SetBytesProcessed( - static_cast(state.iterations())*state.range(0)); -} -BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue)->Range(1<<0, 1<<10); -``` - -Three macros are provided for adding benchmark templates. - -```c++ -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE(func, ...) // Takes any number of parameters. -#else // C++ < C++11 -#define BENCHMARK_TEMPLATE(func, arg1) -#endif -#define BENCHMARK_TEMPLATE1(func, arg1) -#define BENCHMARK_TEMPLATE2(func, arg1, arg2) -``` - - - -### Fixtures - -Fixture tests are created by first defining a type that derives from -`::benchmark::Fixture` and then creating/registering the tests using the -following macros: - -* `BENCHMARK_F(ClassName, Method)` -* `BENCHMARK_DEFINE_F(ClassName, Method)` -* `BENCHMARK_REGISTER_F(ClassName, Method)` - -For Example: - -```c++ -class MyFixture : public benchmark::Fixture { -public: - void SetUp(const ::benchmark::State& state) { - } - - void TearDown(const ::benchmark::State& state) { - } -}; - -BENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) { - for (auto _ : st) { - ... - } -} - -BENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) { - for (auto _ : st) { - ... - } -} -/* BarTest is NOT registered */ -BENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2); -/* BarTest is now registered */ -``` - -#### Templated Fixtures - -Also you can create templated fixture by using the following macros: - -* `BENCHMARK_TEMPLATE_F(ClassName, Method, ...)` -* `BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)` - -For example: -```c++ -template -class MyFixture : public benchmark::Fixture {}; - -BENCHMARK_TEMPLATE_F(MyFixture, IntTest, int)(benchmark::State& st) { - for (auto _ : st) { - ... - } -} - -BENCHMARK_TEMPLATE_DEFINE_F(MyFixture, DoubleTest, double)(benchmark::State& st) { - for (auto _ : st) { - ... - } -} - -BENCHMARK_REGISTER_F(MyFixture, DoubleTest)->Threads(2); -``` - - - -### Custom Counters - -You can add your own counters with user-defined names. The example below -will add columns "Foo", "Bar" and "Baz" in its output: - -```c++ -static void UserCountersExample1(benchmark::State& state) { - double numFoos = 0, numBars = 0, numBazs = 0; - for (auto _ : state) { - // ... count Foo,Bar,Baz events - } - state.counters["Foo"] = numFoos; - state.counters["Bar"] = numBars; - state.counters["Baz"] = numBazs; -} -``` - -The `state.counters` object is a `std::map` with `std::string` keys -and `Counter` values. The latter is a `double`-like class, via an implicit -conversion to `double&`. Thus you can use all of the standard arithmetic -assignment operators (`=,+=,-=,*=,/=`) to change the value of each counter. - -In multithreaded benchmarks, each counter is set on the calling thread only. -When the benchmark finishes, the counters from each thread will be summed; -the resulting sum is the value which will be shown for the benchmark. - -The `Counter` constructor accepts three parameters: the value as a `double` -; a bit flag which allows you to show counters as rates, and/or as per-thread -iteration, and/or as per-thread averages, and/or iteration invariants; -and a flag specifying the 'unit' - i.e. is 1k a 1000 (default, -`benchmark::Counter::OneK::kIs1000`), or 1024 -(`benchmark::Counter::OneK::kIs1024`)? - -```c++ - // sets a simple counter - state.counters["Foo"] = numFoos; - - // Set the counter as a rate. It will be presented divided - // by the duration of the benchmark. - state.counters["FooRate"] = Counter(numFoos, benchmark::Counter::kIsRate); - - // Set the counter as a thread-average quantity. It will - // be presented divided by the number of threads. - state.counters["FooAvg"] = Counter(numFoos, benchmark::Counter::kAvgThreads); - - // There's also a combined flag: - state.counters["FooAvgRate"] = Counter(numFoos,benchmark::Counter::kAvgThreadsRate); - - // This says that we process with the rate of state.range(0) bytes every iteration: - state.counters["BytesProcessed"] = Counter(state.range(0), benchmark::Counter::kIsIterationInvariantRate, benchmark::Counter::OneK::kIs1024); -``` - -When you're compiling in C++11 mode or later you can use `insert()` with -`std::initializer_list`: - -```c++ - // With C++11, this can be done: - state.counters.insert({{"Foo", numFoos}, {"Bar", numBars}, {"Baz", numBazs}}); - // ... instead of: - state.counters["Foo"] = numFoos; - state.counters["Bar"] = numBars; - state.counters["Baz"] = numBazs; -``` - -#### Counter Reporting - -When using the console reporter, by default, user counters are are printed at -the end after the table, the same way as ``bytes_processed`` and -``items_processed``. This is best for cases in which there are few counters, -or where there are only a couple of lines per benchmark. Here's an example of -the default output: - -``` ------------------------------------------------------------------------------- -Benchmark Time CPU Iterations UserCounters... ------------------------------------------------------------------------------- -BM_UserCounter/threads:8 2248 ns 10277 ns 68808 Bar=16 Bat=40 Baz=24 Foo=8 -BM_UserCounter/threads:1 9797 ns 9788 ns 71523 Bar=2 Bat=5 Baz=3 Foo=1024m -BM_UserCounter/threads:2 4924 ns 9842 ns 71036 Bar=4 Bat=10 Baz=6 Foo=2 -BM_UserCounter/threads:4 2589 ns 10284 ns 68012 Bar=8 Bat=20 Baz=12 Foo=4 -BM_UserCounter/threads:8 2212 ns 10287 ns 68040 Bar=16 Bat=40 Baz=24 Foo=8 -BM_UserCounter/threads:16 1782 ns 10278 ns 68144 Bar=32 Bat=80 Baz=48 Foo=16 -BM_UserCounter/threads:32 1291 ns 10296 ns 68256 Bar=64 Bat=160 Baz=96 Foo=32 -BM_UserCounter/threads:4 2615 ns 10307 ns 68040 Bar=8 Bat=20 Baz=12 Foo=4 -BM_Factorial 26 ns 26 ns 26608979 40320 -BM_Factorial/real_time 26 ns 26 ns 26587936 40320 -BM_CalculatePiRange/1 16 ns 16 ns 45704255 0 -BM_CalculatePiRange/8 73 ns 73 ns 9520927 3.28374 -BM_CalculatePiRange/64 609 ns 609 ns 1140647 3.15746 -BM_CalculatePiRange/512 4900 ns 4901 ns 142696 3.14355 -``` - -If this doesn't suit you, you can print each counter as a table column by -passing the flag `--benchmark_counters_tabular=true` to the benchmark -application. This is best for cases in which there are a lot of counters, or -a lot of lines per individual benchmark. Note that this will trigger a -reprinting of the table header any time the counter set changes between -individual benchmarks. Here's an example of corresponding output when -`--benchmark_counters_tabular=true` is passed: - -``` ---------------------------------------------------------------------------------------- -Benchmark Time CPU Iterations Bar Bat Baz Foo ---------------------------------------------------------------------------------------- -BM_UserCounter/threads:8 2198 ns 9953 ns 70688 16 40 24 8 -BM_UserCounter/threads:1 9504 ns 9504 ns 73787 2 5 3 1 -BM_UserCounter/threads:2 4775 ns 9550 ns 72606 4 10 6 2 -BM_UserCounter/threads:4 2508 ns 9951 ns 70332 8 20 12 4 -BM_UserCounter/threads:8 2055 ns 9933 ns 70344 16 40 24 8 -BM_UserCounter/threads:16 1610 ns 9946 ns 70720 32 80 48 16 -BM_UserCounter/threads:32 1192 ns 9948 ns 70496 64 160 96 32 -BM_UserCounter/threads:4 2506 ns 9949 ns 70332 8 20 12 4 --------------------------------------------------------------- -Benchmark Time CPU Iterations --------------------------------------------------------------- -BM_Factorial 26 ns 26 ns 26392245 40320 -BM_Factorial/real_time 26 ns 26 ns 26494107 40320 -BM_CalculatePiRange/1 15 ns 15 ns 45571597 0 -BM_CalculatePiRange/8 74 ns 74 ns 9450212 3.28374 -BM_CalculatePiRange/64 595 ns 595 ns 1173901 3.15746 -BM_CalculatePiRange/512 4752 ns 4752 ns 147380 3.14355 -BM_CalculatePiRange/4k 37970 ns 37972 ns 18453 3.14184 -BM_CalculatePiRange/32k 303733 ns 303744 ns 2305 3.14162 -BM_CalculatePiRange/256k 2434095 ns 2434186 ns 288 3.1416 -BM_CalculatePiRange/1024k 9721140 ns 9721413 ns 71 3.14159 -BM_CalculatePi/threads:8 2255 ns 9943 ns 70936 -``` -Note above the additional header printed when the benchmark changes from -``BM_UserCounter`` to ``BM_Factorial``. This is because ``BM_Factorial`` does -not have the same counter set as ``BM_UserCounter``. - - - -### Multithreaded Benchmarks - -In a multithreaded test (benchmark invoked by multiple threads simultaneously), -it is guaranteed that none of the threads will start until all have reached -the start of the benchmark loop, and all will have finished before any thread -exits the benchmark loop. (This behavior is also provided by the `KeepRunning()` -API) As such, any global setup or teardown can be wrapped in a check against the thread -index: - -```c++ -static void BM_MultiThreaded(benchmark::State& state) { - if (state.thread_index == 0) { - // Setup code here. - } - for (auto _ : state) { - // Run the test as normal. - } - if (state.thread_index == 0) { - // Teardown code here. - } -} -BENCHMARK(BM_MultiThreaded)->Threads(2); -``` - -If the benchmarked code itself uses threads and you want to compare it to -single-threaded code, you may want to use real-time ("wallclock") measurements -for latency comparisons: - -```c++ -BENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime(); -``` - -Without `UseRealTime`, CPU time is used by default. - - - -### CPU Timers - -By default, the CPU timer only measures the time spent by the main thread. -If the benchmark itself uses threads internally, this measurement may not -be what you are looking for. Instead, there is a way to measure the total -CPU usage of the process, by all the threads. - -```c++ -void callee(int i); - -static void MyMain(int size) { -#pragma omp parallel for - for(int i = 0; i < size; i++) - callee(i); -} - -static void BM_OpenMP(benchmark::State& state) { - for (auto _ : state) - MyMain(state.range(0); -} - -// Measure the time spent by the main thread, use it to decide for how long to -// run the benchmark loop. Depending on the internal implementation detail may -// measure to anywhere from near-zero (the overhead spent before/after work -// handoff to worker thread[s]) to the whole single-thread time. -BENCHMARK(BM_OpenMP)->Range(8, 8<<10); - -// Measure the user-visible time, the wall clock (literally, the time that -// has passed on the clock on the wall), use it to decide for how long to -// run the benchmark loop. This will always be meaningful, an will match the -// time spent by the main thread in single-threaded case, in general decreasing -// with the number of internal threads doing the work. -BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->UseRealTime(); - -// Measure the total CPU consumption, use it to decide for how long to -// run the benchmark loop. This will always measure to no less than the -// time spent by the main thread in single-threaded case. -BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime(); - -// A mixture of the last two. Measure the total CPU consumption, but use the -// wall clock to decide for how long to run the benchmark loop. -BENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime()->UseRealTime(); -``` - -#### Controlling Timers - -Normally, the entire duration of the work loop (`for (auto _ : state) {}`) -is measured. But sometimes, it is necessary to do some work inside of -that loop, every iteration, but without counting that time to the benchmark time. -That is possible, althought it is not recommended, since it has high overhead. - -```c++ -static void BM_SetInsert_With_Timer_Control(benchmark::State& state) { - std::set data; - for (auto _ : state) { - state.PauseTiming(); // Stop timers. They will not count until they are resumed. - data = ConstructRandomSet(state.range(0)); // Do something that should not be measured - state.ResumeTiming(); // And resume timers. They are now counting again. - // The rest will be measured. - for (int j = 0; j < state.range(1); ++j) - data.insert(RandomNumber()); - } -} -BENCHMARK(BM_SetInsert_With_Timer_Control)->Ranges({{1<<10, 8<<10}, {128, 512}}); -``` - - - -### Manual Timing - -For benchmarking something for which neither CPU time nor real-time are -correct or accurate enough, completely manual timing is supported using -the `UseManualTime` function. - -When `UseManualTime` is used, the benchmarked code must call -`SetIterationTime` once per iteration of the benchmark loop to -report the manually measured time. - -An example use case for this is benchmarking GPU execution (e.g. OpenCL -or CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot -be accurately measured using CPU time or real-time. Instead, they can be -measured accurately using a dedicated API, and these measurement results -can be reported back with `SetIterationTime`. - -```c++ -static void BM_ManualTiming(benchmark::State& state) { - int microseconds = state.range(0); - std::chrono::duration sleep_duration { - static_cast(microseconds) - }; - - for (auto _ : state) { - auto start = std::chrono::high_resolution_clock::now(); - // Simulate some useful workload with a sleep - std::this_thread::sleep_for(sleep_duration); - auto end = std::chrono::high_resolution_clock::now(); - - auto elapsed_seconds = - std::chrono::duration_cast>( - end - start); - - state.SetIterationTime(elapsed_seconds.count()); - } -} -BENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime(); -``` - - - -### Setting the Time Unit - -If a benchmark runs a few milliseconds it may be hard to visually compare the -measured times, since the output data is given in nanoseconds per default. In -order to manually set the time unit, you can specify it manually: - -```c++ -BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); -``` - - - -### Preventing Optimization - -To prevent a value or expression from being optimized away by the compiler -the `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()` -functions can be used. - -```c++ -static void BM_test(benchmark::State& state) { - for (auto _ : state) { - int x = 0; - for (int i=0; i < 64; ++i) { - benchmark::DoNotOptimize(x += i); - } - } -} -``` - -`DoNotOptimize()` forces the *result* of `` to be stored in either -memory or a register. For GNU based compilers it acts as read/write barrier -for global memory. More specifically it forces the compiler to flush pending -writes to memory and reload any other values as necessary. - -Note that `DoNotOptimize()` does not prevent optimizations on `` -in any way. `` may even be removed entirely when the result is already -known. For example: - -```c++ - /* Example 1: `` is removed entirely. */ - int foo(int x) { return x + 42; } - while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42); - - /* Example 2: Result of '' is only reused */ - int bar(int) __attribute__((const)); - while (...) DoNotOptimize(bar(0)); // Optimized to: - // int __result__ = bar(0); - // while (...) DoNotOptimize(__result__); -``` - -The second tool for preventing optimizations is `ClobberMemory()`. In essence -`ClobberMemory()` forces the compiler to perform all pending writes to global -memory. Memory managed by block scope objects must be "escaped" using -`DoNotOptimize(...)` before it can be clobbered. In the below example -`ClobberMemory()` prevents the call to `v.push_back(42)` from being optimized -away. - -```c++ -static void BM_vector_push_back(benchmark::State& state) { - for (auto _ : state) { - std::vector v; - v.reserve(1); - benchmark::DoNotOptimize(v.data()); // Allow v.data() to be clobbered. - v.push_back(42); - benchmark::ClobberMemory(); // Force 42 to be written to memory. - } -} -``` - -Note that `ClobberMemory()` is only available for GNU or MSVC based compilers. - - - -### Statistics: Reporting the Mean, Median and Standard Deviation of Repeated Benchmarks - -By default each benchmark is run once and that single result is reported. -However benchmarks are often noisy and a single result may not be representative -of the overall behavior. For this reason it's possible to repeatedly rerun the -benchmark. - -The number of runs of each benchmark is specified globally by the -`--benchmark_repetitions` flag or on a per benchmark basis by calling -`Repetitions` on the registered benchmark object. When a benchmark is run more -than once the mean, median and standard deviation of the runs will be reported. - -Additionally the `--benchmark_report_aggregates_only={true|false}`, -`--benchmark_display_aggregates_only={true|false}` flags or -`ReportAggregatesOnly(bool)`, `DisplayAggregatesOnly(bool)` functions can be -used to change how repeated tests are reported. By default the result of each -repeated run is reported. When `report aggregates only` option is `true`, -only the aggregates (i.e. mean, median and standard deviation, maybe complexity -measurements if they were requested) of the runs is reported, to both the -reporters - standard output (console), and the file. -However when only the `display aggregates only` option is `true`, -only the aggregates are displayed in the standard output, while the file -output still contains everything. -Calling `ReportAggregatesOnly(bool)` / `DisplayAggregatesOnly(bool)` on a -registered benchmark object overrides the value of the appropriate flag for that -benchmark. - - - -### Custom Statistics - -While having mean, median and standard deviation is nice, this may not be -enough for everyone. For example you may want to know what the largest -observation is, e.g. because you have some real-time constraints. This is easy. -The following code will specify a custom statistic to be calculated, defined -by a lambda function. - -```c++ -void BM_spin_empty(benchmark::State& state) { - for (auto _ : state) { - for (int x = 0; x < state.range(0); ++x) { - benchmark::DoNotOptimize(x); - } - } -} - -BENCHMARK(BM_spin_empty) - ->ComputeStatistics("max", [](const std::vector& v) -> double { - return *(std::max_element(std::begin(v), std::end(v))); - }) - ->Arg(512); -``` - - - -### Using RegisterBenchmark(name, fn, args...) - -The `RegisterBenchmark(name, func, args...)` function provides an alternative -way to create and register benchmarks. -`RegisterBenchmark(name, func, args...)` creates, registers, and returns a -pointer to a new benchmark with the specified `name` that invokes -`func(st, args...)` where `st` is a `benchmark::State` object. - -Unlike the `BENCHMARK` registration macros, which can only be used at the global -scope, the `RegisterBenchmark` can be called anywhere. This allows for -benchmark tests to be registered programmatically. - -Additionally `RegisterBenchmark` allows any callable object to be registered -as a benchmark. Including capturing lambdas and function objects. - -For Example: -```c++ -auto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ }; - -int main(int argc, char** argv) { - for (auto& test_input : { /* ... */ }) - benchmark::RegisterBenchmark(test_input.name(), BM_test, test_input); - benchmark::Initialize(&argc, argv); - benchmark::RunSpecifiedBenchmarks(); -} -``` - - - -### Exiting with an Error - -When errors caused by external influences, such as file I/O and network -communication, occur within a benchmark the -`State::SkipWithError(const char* msg)` function can be used to skip that run -of benchmark and report the error. Note that only future iterations of the -`KeepRunning()` are skipped. For the ranged-for version of the benchmark loop -Users must explicitly exit the loop, otherwise all iterations will be performed. -Users may explicitly return to exit the benchmark immediately. - -The `SkipWithError(...)` function may be used at any point within the benchmark, -including before and after the benchmark loop. - -For example: - -```c++ -static void BM_test(benchmark::State& state) { - auto resource = GetResource(); - if (!resource.good()) { - state.SkipWithError("Resource is not good!"); - // KeepRunning() loop will not be entered. - } - for (state.KeepRunning()) { - auto data = resource.read_data(); - if (!resource.good()) { - state.SkipWithError("Failed to read data!"); - break; // Needed to skip the rest of the iteration. - } - do_stuff(data); - } -} - -static void BM_test_ranged_fo(benchmark::State & state) { - state.SkipWithError("test will not be entered"); - for (auto _ : state) { - state.SkipWithError("Failed!"); - break; // REQUIRED to prevent all further iterations. - } -} -``` - - -### A Faster KeepRunning Loop - -In C++11 mode, a ranged-based for loop should be used in preference to -the `KeepRunning` loop for running the benchmarks. For example: - -```c++ -static void BM_Fast(benchmark::State &state) { - for (auto _ : state) { - FastOperation(); - } -} -BENCHMARK(BM_Fast); -``` - -The reason the ranged-for loop is faster than using `KeepRunning`, is -because `KeepRunning` requires a memory load and store of the iteration count -ever iteration, whereas the ranged-for variant is able to keep the iteration count -in a register. - -For example, an empty inner loop of using the ranged-based for method looks like: - -```asm -# Loop Init - mov rbx, qword ptr [r14 + 104] - call benchmark::State::StartKeepRunning() - test rbx, rbx - je .LoopEnd -.LoopHeader: # =>This Inner Loop Header: Depth=1 - add rbx, -1 - jne .LoopHeader -.LoopEnd: -``` - -Compared to an empty `KeepRunning` loop, which looks like: - -```asm -.LoopHeader: # in Loop: Header=BB0_3 Depth=1 - cmp byte ptr [rbx], 1 - jne .LoopInit -.LoopBody: # =>This Inner Loop Header: Depth=1 - mov rax, qword ptr [rbx + 8] - lea rcx, [rax + 1] - mov qword ptr [rbx + 8], rcx - cmp rax, qword ptr [rbx + 104] - jb .LoopHeader - jmp .LoopEnd -.LoopInit: - mov rdi, rbx - call benchmark::State::StartKeepRunning() - jmp .LoopBody -.LoopEnd: -``` - -Unless C++03 compatibility is required, the ranged-for variant of writing -the benchmark loop should be preferred. - - - -### Disabling CPU Frequency Scaling -If you see this error: -``` -***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead. -``` -you might want to disable the CPU frequency scaling while running the benchmark: -```bash -sudo cpupower frequency-set --governor performance -./mybench -sudo cpupower frequency-set --governor powersave -``` diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/WORKSPACE b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/WORKSPACE deleted file mode 100644 index 9a75f968d91..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/WORKSPACE +++ /dev/null @@ -1,9 +0,0 @@ -workspace(name = "com_github_google_benchmark") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -http_archive( - name = "com_google_googletest", - urls = ["https://github.com/google/googletest/archive/3f0cf6b62ad1eb50d8736538363d3580dd640c3e.zip"], - strip_prefix = "googletest-3f0cf6b62ad1eb50d8736538363d3580dd640c3e", -) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/_config.yml b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/_config.yml deleted file mode 100644 index 18854876c67..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/_config.yml +++ /dev/null @@ -1 +0,0 @@ -theme: jekyll-theme-midnight \ No newline at end of file diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/appveyor.yml b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/appveyor.yml deleted file mode 100644 index cf240190bea..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/appveyor.yml +++ /dev/null @@ -1,50 +0,0 @@ -version: '{build}' - -image: Visual Studio 2017 - -configuration: - - Debug - - Release - -environment: - matrix: - - compiler: msvc-15-seh - generator: "Visual Studio 15 2017" - - - compiler: msvc-15-seh - generator: "Visual Studio 15 2017 Win64" - - - compiler: msvc-14-seh - generator: "Visual Studio 14 2015" - - - compiler: msvc-14-seh - generator: "Visual Studio 14 2015 Win64" - - - compiler: gcc-5.3.0-posix - generator: "MinGW Makefiles" - cxx_path: 'C:\mingw-w64\i686-5.3.0-posix-dwarf-rt_v4-rev0\mingw32\bin' - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 - -matrix: - fast_finish: true - -install: - # git bash conflicts with MinGW makefiles - - if "%generator%"=="MinGW Makefiles" (set "PATH=%PATH:C:\Program Files\Git\usr\bin;=%") - - if not "%cxx_path%"=="" (set "PATH=%PATH%;%cxx_path%") - -build_script: - - md _build -Force - - cd _build - - echo %configuration% - - cmake -G "%generator%" "-DCMAKE_BUILD_TYPE=%configuration%" -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON .. - - cmake --build . --config %configuration% - -test_script: - - ctest -c %configuration% --timeout 300 --output-on-failure - -artifacts: - - path: '_build/CMakeFiles/*.log' - name: logs - - path: '_build/Testing/**/*.xml' - name: test_results diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/AddCXXCompilerFlag.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/AddCXXCompilerFlag.cmake deleted file mode 100644 index d0d20998144..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/AddCXXCompilerFlag.cmake +++ /dev/null @@ -1,74 +0,0 @@ -# - Adds a compiler flag if it is supported by the compiler -# -# This function checks that the supplied compiler flag is supported and then -# adds it to the corresponding compiler flags -# -# add_cxx_compiler_flag( []) -# -# - Example -# -# include(AddCXXCompilerFlag) -# add_cxx_compiler_flag(-Wall) -# add_cxx_compiler_flag(-no-strict-aliasing RELEASE) -# Requires CMake 2.6+ - -if(__add_cxx_compiler_flag) - return() -endif() -set(__add_cxx_compiler_flag INCLUDED) - -include(CheckCXXCompilerFlag) - -function(mangle_compiler_flag FLAG OUTPUT) - string(TOUPPER "HAVE_CXX_FLAG_${FLAG}" SANITIZED_FLAG) - string(REPLACE "+" "X" SANITIZED_FLAG ${SANITIZED_FLAG}) - string(REGEX REPLACE "[^A-Za-z_0-9]" "_" SANITIZED_FLAG ${SANITIZED_FLAG}) - string(REGEX REPLACE "_+" "_" SANITIZED_FLAG ${SANITIZED_FLAG}) - set(${OUTPUT} "${SANITIZED_FLAG}" PARENT_SCOPE) -endfunction(mangle_compiler_flag) - -function(add_cxx_compiler_flag FLAG) - mangle_compiler_flag("${FLAG}" MANGLED_FLAG) - set(OLD_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${FLAG}") - check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) - set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") - if(${MANGLED_FLAG}) - set(VARIANT ${ARGV1}) - if(ARGV1) - string(TOUPPER "_${VARIANT}" VARIANT) - endif() - set(CMAKE_CXX_FLAGS${VARIANT} "${CMAKE_CXX_FLAGS${VARIANT}} ${BENCHMARK_CXX_FLAGS${VARIANT}} ${FLAG}" PARENT_SCOPE) - endif() -endfunction() - -function(add_required_cxx_compiler_flag FLAG) - mangle_compiler_flag("${FLAG}" MANGLED_FLAG) - set(OLD_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${FLAG}") - check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) - set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") - if(${MANGLED_FLAG}) - set(VARIANT ${ARGV1}) - if(ARGV1) - string(TOUPPER "_${VARIANT}" VARIANT) - endif() - set(CMAKE_CXX_FLAGS${VARIANT} "${CMAKE_CXX_FLAGS${VARIANT}} ${FLAG}" PARENT_SCOPE) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) - set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${FLAG}" PARENT_SCOPE) - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${FLAG}" PARENT_SCOPE) - else() - message(FATAL_ERROR "Required flag '${FLAG}' is not supported by the compiler") - endif() -endfunction() - -function(check_cxx_warning_flag FLAG) - mangle_compiler_flag("${FLAG}" MANGLED_FLAG) - set(OLD_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") - # Add -Werror to ensure the compiler generates an error if the warning flag - # doesn't exist. - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror ${FLAG}") - check_cxx_compiler_flag("${FLAG}" ${MANGLED_FLAG}) - set(CMAKE_REQUIRED_FLAGS "${OLD_CMAKE_REQUIRED_FLAGS}") -endfunction() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/CXXFeatureCheck.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/CXXFeatureCheck.cmake deleted file mode 100644 index 99b56dd6239..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/CXXFeatureCheck.cmake +++ /dev/null @@ -1,64 +0,0 @@ -# - Compile and run code to check for C++ features -# -# This functions compiles a source file under the `cmake` folder -# and adds the corresponding `HAVE_[FILENAME]` flag to the CMake -# environment -# -# cxx_feature_check( []) -# -# - Example -# -# include(CXXFeatureCheck) -# cxx_feature_check(STD_REGEX) -# Requires CMake 2.8.12+ - -if(__cxx_feature_check) - return() -endif() -set(__cxx_feature_check INCLUDED) - -function(cxx_feature_check FILE) - string(TOLOWER ${FILE} FILE) - string(TOUPPER ${FILE} VAR) - string(TOUPPER "HAVE_${VAR}" FEATURE) - if (DEFINED HAVE_${VAR}) - set(HAVE_${VAR} 1 PARENT_SCOPE) - add_definitions(-DHAVE_${VAR}) - return() - endif() - - if (NOT DEFINED COMPILE_${FEATURE}) - message(STATUS "Performing Test ${FEATURE}") - if(CMAKE_CROSSCOMPILING) - try_compile(COMPILE_${FEATURE} - ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${FILE}.cpp - CMAKE_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS} - LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES}) - if(COMPILE_${FEATURE}) - message(WARNING - "If you see build failures due to cross compilation, try setting HAVE_${VAR} to 0") - set(RUN_${FEATURE} 0) - else() - set(RUN_${FEATURE} 1) - endif() - else() - message(STATUS "Performing Test ${FEATURE}") - try_run(RUN_${FEATURE} COMPILE_${FEATURE} - ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${FILE}.cpp - CMAKE_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS} - LINK_LIBRARIES ${BENCHMARK_CXX_LIBRARIES}) - endif() - endif() - - if(RUN_${FEATURE} EQUAL 0) - message(STATUS "Performing Test ${FEATURE} -- success") - set(HAVE_${VAR} 1 PARENT_SCOPE) - add_definitions(-DHAVE_${VAR}) - else() - if(NOT COMPILE_${FEATURE}) - message(STATUS "Performing Test ${FEATURE} -- failed to compile") - else() - message(STATUS "Performing Test ${FEATURE} -- compiled but failed to run") - endif() - endif() -endfunction() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/Config.cmake.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/Config.cmake.in deleted file mode 100644 index 6e9256eea8a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/Config.cmake.in +++ /dev/null @@ -1 +0,0 @@ -include("${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake") diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/GetGitVersion.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/GetGitVersion.cmake deleted file mode 100644 index 4f10f226d7a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/GetGitVersion.cmake +++ /dev/null @@ -1,54 +0,0 @@ -# - Returns a version string from Git tags -# -# This function inspects the annotated git tags for the project and returns a string -# into a CMake variable -# -# get_git_version() -# -# - Example -# -# include(GetGitVersion) -# get_git_version(GIT_VERSION) -# -# Requires CMake 2.8.11+ -find_package(Git) - -if(__get_git_version) - return() -endif() -set(__get_git_version INCLUDED) - -function(get_git_version var) - if(GIT_EXECUTABLE) - execute_process(COMMAND ${GIT_EXECUTABLE} describe --match "v[0-9]*.[0-9]*.[0-9]*" --abbrev=8 - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - RESULT_VARIABLE status - OUTPUT_VARIABLE GIT_VERSION - ERROR_QUIET) - if(${status}) - set(GIT_VERSION "v0.0.0") - else() - string(STRIP ${GIT_VERSION} GIT_VERSION) - string(REGEX REPLACE "-[0-9]+-g" "-" GIT_VERSION ${GIT_VERSION}) - endif() - - # Work out if the repository is dirty - execute_process(COMMAND ${GIT_EXECUTABLE} update-index -q --refresh - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - OUTPUT_QUIET - ERROR_QUIET) - execute_process(COMMAND ${GIT_EXECUTABLE} diff-index --name-only HEAD -- - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - OUTPUT_VARIABLE GIT_DIFF_INDEX - ERROR_QUIET) - string(COMPARE NOTEQUAL "${GIT_DIFF_INDEX}" "" GIT_DIRTY) - if (${GIT_DIRTY}) - set(GIT_VERSION "${GIT_VERSION}-dirty") - endif() - else() - set(GIT_VERSION "v0.0.0") - endif() - - message(STATUS "git Version: ${GIT_VERSION}") - set(${var} ${GIT_VERSION} PARENT_SCOPE) -endfunction() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/GoogleTest.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/GoogleTest.cmake deleted file mode 100644 index fb7c6be25e0..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/GoogleTest.cmake +++ /dev/null @@ -1,41 +0,0 @@ -# Download and unpack googletest at configure time -set(GOOGLETEST_PREFIX "${benchmark_BINARY_DIR}/third_party/googletest") -configure_file(${benchmark_SOURCE_DIR}/cmake/GoogleTest.cmake.in ${GOOGLETEST_PREFIX}/CMakeLists.txt @ONLY) - -set(GOOGLETEST_PATH "${CMAKE_CURRENT_SOURCE_DIR}/googletest") # Mind the quotes -execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" - -DALLOW_DOWNLOADING_GOOGLETEST=${BENCHMARK_DOWNLOAD_DEPENDENCIES} -DGOOGLETEST_PATH:PATH=${GOOGLETEST_PATH} . - RESULT_VARIABLE result - WORKING_DIRECTORY ${GOOGLETEST_PREFIX} -) - -if(result) - message(FATAL_ERROR "CMake step for googletest failed: ${result}") -endif() - -execute_process( - COMMAND ${CMAKE_COMMAND} --build . - RESULT_VARIABLE result - WORKING_DIRECTORY ${GOOGLETEST_PREFIX} -) - -if(result) - message(FATAL_ERROR "Build step for googletest failed: ${result}") -endif() - -# Prevent overriding the parent project's compiler/linker -# settings on Windows -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) - -include(${GOOGLETEST_PREFIX}/googletest-paths.cmake) - -# Add googletest directly to our build. This defines -# the gtest and gtest_main targets. -add_subdirectory(${GOOGLETEST_SOURCE_DIR} - ${GOOGLETEST_BINARY_DIR} - EXCLUDE_FROM_ALL) - -set_target_properties(gtest PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $) -set_target_properties(gtest_main PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $) -set_target_properties(gmock PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $) -set_target_properties(gmock_main PROPERTIES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES $) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/GoogleTest.cmake.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/GoogleTest.cmake.in deleted file mode 100644 index 28818ee2938..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/GoogleTest.cmake.in +++ /dev/null @@ -1,58 +0,0 @@ -cmake_minimum_required(VERSION 2.8.12) - -project(googletest-download NONE) - -# Enable ExternalProject CMake module -include(ExternalProject) - -option(ALLOW_DOWNLOADING_GOOGLETEST "If googletest src tree is not found in location specified by GOOGLETEST_PATH, do fetch the archive from internet" OFF) -set(GOOGLETEST_PATH "/usr/src/googletest" CACHE PATH - "Path to the googletest root tree. Should contain googletest and googlemock subdirs. And CMakeLists.txt in root, and in both of these subdirs") - -# Download and install GoogleTest - -message(STATUS "Looking for Google Test sources") -message(STATUS "Looking for Google Test sources in ${GOOGLETEST_PATH}") -if(EXISTS "${GOOGLETEST_PATH}" AND IS_DIRECTORY "${GOOGLETEST_PATH}" AND EXISTS "${GOOGLETEST_PATH}/CMakeLists.txt" AND - EXISTS "${GOOGLETEST_PATH}/googletest" AND IS_DIRECTORY "${GOOGLETEST_PATH}/googletest" AND EXISTS "${GOOGLETEST_PATH}/googletest/CMakeLists.txt" AND - EXISTS "${GOOGLETEST_PATH}/googlemock" AND IS_DIRECTORY "${GOOGLETEST_PATH}/googlemock" AND EXISTS "${GOOGLETEST_PATH}/googlemock/CMakeLists.txt") - message(STATUS "Found Google Test in ${GOOGLETEST_PATH}") - - ExternalProject_Add( - googletest - PREFIX "${CMAKE_BINARY_DIR}" - DOWNLOAD_DIR "${CMAKE_BINARY_DIR}/download" - SOURCE_DIR "${GOOGLETEST_PATH}" # use existing src dir. - BINARY_DIR "${CMAKE_BINARY_DIR}/build" - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" - TEST_COMMAND "" - ) -else() - if(NOT ALLOW_DOWNLOADING_GOOGLETEST) - message(SEND_ERROR "Did not find Google Test sources! Either pass correct path in GOOGLETEST_PATH, or enable ALLOW_DOWNLOADING_GOOGLETEST, or disable BENCHMARK_ENABLE_GTEST_TESTS / BENCHMARK_ENABLE_TESTING.") - else() - message(WARNING "Did not find Google Test sources! Fetching from web...") - ExternalProject_Add( - googletest - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG master - PREFIX "${CMAKE_BINARY_DIR}" - STAMP_DIR "${CMAKE_BINARY_DIR}/stamp" - DOWNLOAD_DIR "${CMAKE_BINARY_DIR}/download" - SOURCE_DIR "${CMAKE_BINARY_DIR}/src" - BINARY_DIR "${CMAKE_BINARY_DIR}/build" - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" - TEST_COMMAND "" - ) - endif() -endif() - -ExternalProject_Get_Property(googletest SOURCE_DIR BINARY_DIR) -file(WRITE googletest-paths.cmake -"set(GOOGLETEST_SOURCE_DIR \"${SOURCE_DIR}\") -set(GOOGLETEST_BINARY_DIR \"${BINARY_DIR}\") -") diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/benchmark.pc.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/benchmark.pc.in deleted file mode 100644 index 43ca8f91d70..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/benchmark.pc.in +++ /dev/null @@ -1,12 +0,0 @@ -prefix=@CMAKE_INSTALL_PREFIX@ -exec_prefix=${prefix} -libdir=${prefix}/lib -includedir=${prefix}/include - -Name: @PROJECT_NAME@ -Description: Google microbenchmark framework -Version: @VERSION@ - -Libs: -L${libdir} -lbenchmark -Libs.private: -lpthread -Cflags: -I${includedir} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/gnu_posix_regex.cpp b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/gnu_posix_regex.cpp deleted file mode 100644 index b5b91cdab7c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/gnu_posix_regex.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include -int main() { - std::string str = "test0159"; - regex_t re; - int ec = regcomp(&re, "^[a-z]+[0-9]+$", REG_EXTENDED | REG_NOSUB); - if (ec != 0) { - return ec; - } - return regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0; -} - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/llvm-toolchain.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/llvm-toolchain.cmake deleted file mode 100644 index fc119e52fd2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/llvm-toolchain.cmake +++ /dev/null @@ -1,8 +0,0 @@ -find_package(LLVMAr REQUIRED) -set(CMAKE_AR "${LLVMAR_EXECUTABLE}" CACHE FILEPATH "" FORCE) - -find_package(LLVMNm REQUIRED) -set(CMAKE_NM "${LLVMNM_EXECUTABLE}" CACHE FILEPATH "" FORCE) - -find_package(LLVMRanLib REQUIRED) -set(CMAKE_RANLIB "${LLVMRANLIB_EXECUTABLE}" CACHE FILEPATH "" FORCE) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/posix_regex.cpp b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/posix_regex.cpp deleted file mode 100644 index 466dc62560a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/posix_regex.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include -int main() { - std::string str = "test0159"; - regex_t re; - int ec = regcomp(&re, "^[a-z]+[0-9]+$", REG_EXTENDED | REG_NOSUB); - if (ec != 0) { - return ec; - } - int ret = regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0; - regfree(&re); - return ret; -} - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/split_list.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/split_list.cmake deleted file mode 100644 index 67aed3fdc85..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/split_list.cmake +++ /dev/null @@ -1,3 +0,0 @@ -macro(split_list listname) - string(REPLACE ";" " " ${listname} "${${listname}}") -endmacro() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/std_regex.cpp b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/std_regex.cpp deleted file mode 100644 index 696f2a26bce..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/std_regex.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include -#include -int main() { - const std::string str = "test0159"; - std::regex re; - re = std::regex("^[a-z]+[0-9]+$", - std::regex_constants::extended | std::regex_constants::nosubs); - return std::regex_search(str, re) ? 0 : -1; -} - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/steady_clock.cpp b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/steady_clock.cpp deleted file mode 100644 index 66d50d17e9e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/steady_clock.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include - -int main() { - typedef std::chrono::steady_clock Clock; - Clock::time_point tp = Clock::now(); - ((void)tp); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/thread_safety_attributes.cpp b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/thread_safety_attributes.cpp deleted file mode 100644 index 46161babdb1..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/cmake/thread_safety_attributes.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#define HAVE_THREAD_SAFETY_ATTRIBUTES -#include "../src/mutex.h" - -int main() {} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/CMakeLists.txt b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/CMakeLists.txt deleted file mode 100644 index 15b92ca91aa..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 2.8.11) -project(cmake_wrapper) - -include(conanbuildinfo.cmake) -conan_basic_setup() - -include(${CMAKE_SOURCE_DIR}/CMakeListsOriginal.txt) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/test_package/CMakeLists.txt b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/test_package/CMakeLists.txt deleted file mode 100644 index 089a6c729d2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/test_package/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -cmake_minimum_required(VERSION 2.8.11) -project(test_package) - -set(CMAKE_VERBOSE_MAKEFILE TRUE) - -include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) -conan_basic_setup() - -add_executable(${PROJECT_NAME} test_package.cpp) -target_link_libraries(${PROJECT_NAME} ${CONAN_LIBS}) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/test_package/conanfile.py b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/test_package/conanfile.py deleted file mode 100644 index d63f4088c99..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/test_package/conanfile.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from conans import ConanFile, CMake -import os - - -class TestPackageConan(ConanFile): - settings = "os", "compiler", "build_type", "arch" - generators = "cmake" - - def build(self): - cmake = CMake(self) - cmake.configure() - cmake.build() - - def test(self): - bin_path = os.path.join("bin", "test_package") - self.run(bin_path, run_environment=True) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/test_package/test_package.cpp b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/test_package/test_package.cpp deleted file mode 100644 index 4fa7ec0bf9d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conan/test_package/test_package.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "benchmark/benchmark.h" - -void BM_StringCreation(benchmark::State& state) { - while (state.KeepRunning()) - std::string empty_string; -} - -BENCHMARK(BM_StringCreation); - -void BM_StringCopy(benchmark::State& state) { - std::string x = "hello"; - while (state.KeepRunning()) - std::string copy(x); -} - -BENCHMARK(BM_StringCopy); - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conanfile.py b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conanfile.py deleted file mode 100644 index e31fc5268ad..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/conanfile.py +++ /dev/null @@ -1,79 +0,0 @@ -from conans import ConanFile, CMake, tools -from conans.errors import ConanInvalidConfiguration -import shutil -import os - - -class GoogleBenchmarkConan(ConanFile): - name = "benchmark" - description = "A microbenchmark support library." - topics = ("conan", "benchmark", "google", "microbenchmark") - url = "https://github.com/google/benchmark" - homepage = "https://github.com/google/benchmark" - author = "Google Inc." - license = "Apache-2.0" - exports_sources = ["*"] - generators = "cmake" - - settings = "arch", "build_type", "compiler", "os" - options = { - "shared": [True, False], - "fPIC": [True, False], - "enable_lto": [True, False], - "enable_exceptions": [True, False] - } - default_options = {"shared": False, "fPIC": True, "enable_lto": False, "enable_exceptions": True} - - _build_subfolder = "." - - def source(self): - # Wrap the original CMake file to call conan_basic_setup - shutil.move("CMakeLists.txt", "CMakeListsOriginal.txt") - shutil.move(os.path.join("conan", "CMakeLists.txt"), "CMakeLists.txt") - - def config_options(self): - if self.settings.os == "Windows": - if self.settings.compiler == "Visual Studio" and float(self.settings.compiler.version.value) <= 12: - raise ConanInvalidConfiguration("{} {} does not support Visual Studio <= 12".format(self.name, self.version)) - del self.options.fPIC - - def configure(self): - if self.settings.os == "Windows" and self.options.shared: - raise ConanInvalidConfiguration("Windows shared builds are not supported right now, see issue #639") - - def _configure_cmake(self): - cmake = CMake(self) - - cmake.definitions["BENCHMARK_ENABLE_TESTING"] = "OFF" - cmake.definitions["BENCHMARK_ENABLE_GTEST_TESTS"] = "OFF" - cmake.definitions["BENCHMARK_ENABLE_LTO"] = "ON" if self.options.enable_lto else "OFF" - cmake.definitions["BENCHMARK_ENABLE_EXCEPTIONS"] = "ON" if self.options.enable_exceptions else "OFF" - - # See https://github.com/google/benchmark/pull/638 for Windows 32 build explanation - if self.settings.os != "Windows": - cmake.definitions["BENCHMARK_BUILD_32_BITS"] = "ON" if "64" not in str(self.settings.arch) else "OFF" - cmake.definitions["BENCHMARK_USE_LIBCXX"] = "ON" if (str(self.settings.compiler.libcxx) == "libc++") else "OFF" - else: - cmake.definitions["BENCHMARK_USE_LIBCXX"] = "OFF" - - cmake.configure(build_folder=self._build_subfolder) - return cmake - - def build(self): - cmake = self._configure_cmake() - cmake.build() - - def package(self): - cmake = self._configure_cmake() - cmake.install() - - self.copy(pattern="LICENSE", dst="licenses") - - def package_info(self): - self.cpp_info.libs = tools.collect_libs(self) - if self.settings.os == "Linux": - self.cpp_info.libs.extend(["pthread", "rt"]) - elif self.settings.os == "Windows": - self.cpp_info.libs.append("shlwapi") - elif self.settings.os == "SunOS": - self.cpp_info.libs.append("kstat") diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/dependencies.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/dependencies.md deleted file mode 100644 index 6289b4e3548..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/dependencies.md +++ /dev/null @@ -1,18 +0,0 @@ -# Build tool dependency policy - -To ensure the broadest compatibility when building the benchmark library, but -still allow forward progress, we require any build tooling to be available for: - -* Debian stable AND -* The last two Ubuntu LTS releases AND - -Currently, this means using build tool versions that are available for Ubuntu -16.04 (Xenial), Ubuntu 18.04 (Bionic), and Debian stretch. - -_Note, [travis](.travis.yml) runs under Ubuntu 14.04 (Trusty) for linux builds._ - -## cmake -The current supported version is cmake 3.5.1 as of 2018-06-06. - -_Note, this version is also available for Ubuntu 14.04, the previous Ubuntu LTS -release, as `cmake3`._ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/docs/AssemblyTests.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/docs/AssemblyTests.md deleted file mode 100644 index 1fbdc269b53..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/docs/AssemblyTests.md +++ /dev/null @@ -1,147 +0,0 @@ -# Assembly Tests - -The Benchmark library provides a number of functions whose primary -purpose in to affect assembly generation, including `DoNotOptimize` -and `ClobberMemory`. In addition there are other functions, -such as `KeepRunning`, for which generating good assembly is paramount. - -For these functions it's important to have tests that verify the -correctness and quality of the implementation. This requires testing -the code generated by the compiler. - -This document describes how the Benchmark library tests compiler output, -as well as how to properly write new tests. - - -## Anatomy of a Test - -Writing a test has two steps: - -* Write the code you want to generate assembly for. -* Add `// CHECK` lines to match against the verified assembly. - -Example: -```c++ - -// CHECK-LABEL: test_add: -extern "C" int test_add() { - extern int ExternInt; - return ExternInt + 1; - - // CHECK: movl ExternInt(%rip), %eax - // CHECK: addl %eax - // CHECK: ret -} - -``` - -#### LLVM Filecheck - -[LLVM's Filecheck](https://llvm.org/docs/CommandGuide/FileCheck.html) -is used to test the generated assembly against the `// CHECK` lines -specified in the tests source file. Please see the documentation -linked above for information on how to write `CHECK` directives. - -#### Tips and Tricks: - -* Tests should match the minimal amount of output required to establish -correctness. `CHECK` directives don't have to match on the exact next line -after the previous match, so tests should omit checks for unimportant -bits of assembly. ([`CHECK-NEXT`](https://llvm.org/docs/CommandGuide/FileCheck.html#the-check-next-directive) -can be used to ensure a match occurs exactly after the previous match). - -* The tests are compiled with `-O3 -g0`. So we're only testing the -optimized output. - -* The assembly output is further cleaned up using `tools/strip_asm.py`. -This removes comments, assembler directives, and unused labels before -the test is run. - -* The generated and stripped assembly file for a test is output under -`/test/.s` - -* Filecheck supports using [`CHECK` prefixes](https://llvm.org/docs/CommandGuide/FileCheck.html#cmdoption-check-prefixes) -to specify lines that should only match in certain situations. -The Benchmark tests use `CHECK-CLANG` and `CHECK-GNU` for lines that -are only expected to match Clang or GCC's output respectively. Normal -`CHECK` lines match against all compilers. (Note: `CHECK-NOT` and -`CHECK-LABEL` are NOT prefixes. They are versions of non-prefixed -`CHECK` lines) - -* Use `extern "C"` to disable name mangling for specific functions. This -makes them easier to name in the `CHECK` lines. - - -## Problems Writing Portable Tests - -Writing tests which check the code generated by a compiler are -inherently non-portable. Different compilers and even different compiler -versions may generate entirely different code. The Benchmark tests -must tolerate this. - -LLVM Filecheck provides a number of mechanisms to help write -"more portable" tests; including [matching using regular expressions](https://llvm.org/docs/CommandGuide/FileCheck.html#filecheck-pattern-matching-syntax), -allowing the creation of [named variables](https://llvm.org/docs/CommandGuide/FileCheck.html#filecheck-variables) -for later matching, and [checking non-sequential matches](https://llvm.org/docs/CommandGuide/FileCheck.html#the-check-dag-directive). - -#### Capturing Variables - -For example, say GCC stores a variable in a register but Clang stores -it in memory. To write a test that tolerates both cases we "capture" -the destination of the store, and then use the captured expression -to write the remainder of the test. - -```c++ -// CHECK-LABEL: test_div_no_op_into_shr: -extern "C" void test_div_no_op_into_shr(int value) { - int divisor = 2; - benchmark::DoNotOptimize(divisor); // hide the value from the optimizer - return value / divisor; - - // CHECK: movl $2, [[DEST:.*]] - // CHECK: idivl [[DEST]] - // CHECK: ret -} -``` - -#### Using Regular Expressions to Match Differing Output - -Often tests require testing assembly lines which may subtly differ -between compilers or compiler versions. A common example of this -is matching stack frame addresses. In this case regular expressions -can be used to match the differing bits of output. For example: - -```c++ -int ExternInt; -struct Point { int x, y, z; }; - -// CHECK-LABEL: test_store_point: -extern "C" void test_store_point() { - Point p{ExternInt, ExternInt, ExternInt}; - benchmark::DoNotOptimize(p); - - // CHECK: movl ExternInt(%rip), %eax - // CHECK: movl %eax, -{{[0-9]+}}(%rsp) - // CHECK: movl %eax, -{{[0-9]+}}(%rsp) - // CHECK: movl %eax, -{{[0-9]+}}(%rsp) - // CHECK: ret -} -``` - -## Current Requirements and Limitations - -The tests require Filecheck to be installed along the `PATH` of the -build machine. Otherwise the tests will be disabled. - -Additionally, as mentioned in the previous section, codegen tests are -inherently non-portable. Currently the tests are limited to: - -* x86_64 targets. -* Compiled with GCC or Clang - -Further work could be done, at least on a limited basis, to extend the -tests to other architectures and compilers (using `CHECK` prefixes). - -Furthermore, the tests fail for builds which specify additional flags -that modify code generation, including `--coverage` or `-fsanitize=`. - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/docs/_config.yml b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/docs/_config.yml deleted file mode 100644 index 18854876c67..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/docs/_config.yml +++ /dev/null @@ -1 +0,0 @@ -theme: jekyll-theme-midnight \ No newline at end of file diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/docs/tools.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/docs/tools.md deleted file mode 100644 index 4a3b2e9bd2c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/docs/tools.md +++ /dev/null @@ -1,199 +0,0 @@ -# Benchmark Tools - -## compare.py - -The `compare.py` can be used to compare the result of benchmarks. - -**NOTE**: the utility relies on the scipy package which can be installed using [these instructions](https://www.scipy.org/install.html). - -### Displaying aggregates only - -The switch `-a` / `--display_aggregates_only` can be used to control the -displayment of the normal iterations vs the aggregates. When passed, it will -be passthrough to the benchmark binaries to be run, and will be accounted for -in the tool itself; only the aggregates will be displayed, but not normal runs. -It only affects the display, the separate runs will still be used to calculate -the U test. - -### Modes of operation - -There are three modes of operation: - -1. Just compare two benchmarks -The program is invoked like: - -``` bash -$ compare.py benchmarks [benchmark options]... -``` -Where `` and `` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file. - -`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes. - -Example output: -``` -$ ./compare.py benchmarks ./a.out ./a.out -RUNNING: ./a.out --benchmark_out=/tmp/tmprBT5nW -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:16:44 ------------------------------------------------------- -Benchmark Time CPU Iterations ------------------------------------------------------- -BM_memcpy/8 36 ns 36 ns 19101577 211.669MB/s -BM_memcpy/64 76 ns 76 ns 9412571 800.199MB/s -BM_memcpy/512 84 ns 84 ns 8249070 5.64771GB/s -BM_memcpy/1024 116 ns 116 ns 6181763 8.19505GB/s -BM_memcpy/8192 643 ns 643 ns 1062855 11.8636GB/s -BM_copy/8 222 ns 222 ns 3137987 34.3772MB/s -BM_copy/64 1608 ns 1608 ns 432758 37.9501MB/s -BM_copy/512 12589 ns 12589 ns 54806 38.7867MB/s -BM_copy/1024 25169 ns 25169 ns 27713 38.8003MB/s -BM_copy/8192 201165 ns 201112 ns 3486 38.8466MB/s -RUNNING: ./a.out --benchmark_out=/tmp/tmpt1wwG_ -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:16:53 ------------------------------------------------------- -Benchmark Time CPU Iterations ------------------------------------------------------- -BM_memcpy/8 36 ns 36 ns 19397903 211.255MB/s -BM_memcpy/64 73 ns 73 ns 9691174 839.635MB/s -BM_memcpy/512 85 ns 85 ns 8312329 5.60101GB/s -BM_memcpy/1024 118 ns 118 ns 6438774 8.11608GB/s -BM_memcpy/8192 656 ns 656 ns 1068644 11.6277GB/s -BM_copy/8 223 ns 223 ns 3146977 34.2338MB/s -BM_copy/64 1611 ns 1611 ns 435340 37.8751MB/s -BM_copy/512 12622 ns 12622 ns 54818 38.6844MB/s -BM_copy/1024 25257 ns 25239 ns 27779 38.6927MB/s -BM_copy/8192 205013 ns 205010 ns 3479 38.108MB/s -Comparing ./a.out to ./a.out -Benchmark Time CPU Time Old Time New CPU Old CPU New ------------------------------------------------------------------------------------------------------- -BM_memcpy/8 +0.0020 +0.0020 36 36 36 36 -BM_memcpy/64 -0.0468 -0.0470 76 73 76 73 -BM_memcpy/512 +0.0081 +0.0083 84 85 84 85 -BM_memcpy/1024 +0.0098 +0.0097 116 118 116 118 -BM_memcpy/8192 +0.0200 +0.0203 643 656 643 656 -BM_copy/8 +0.0046 +0.0042 222 223 222 223 -BM_copy/64 +0.0020 +0.0020 1608 1611 1608 1611 -BM_copy/512 +0.0027 +0.0026 12589 12622 12589 12622 -BM_copy/1024 +0.0035 +0.0028 25169 25257 25169 25239 -BM_copy/8192 +0.0191 +0.0194 201165 205013 201112 205010 -``` - -What it does is for the every benchmark from the first run it looks for the benchmark with exactly the same name in the second run, and then compares the results. If the names differ, the benchmark is omitted from the diff. -As you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`. - -2. Compare two different filters of one benchmark -The program is invoked like: - -``` bash -$ compare.py filters [benchmark options]... -``` -Where `` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file. - -Where `` and `` are the same regex filters that you would pass to the `[--benchmark_filter=]` parameter of the benchmark binary. - -`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes. - -Example output: -``` -$ ./compare.py filters ./a.out BM_memcpy BM_copy -RUNNING: ./a.out --benchmark_filter=BM_memcpy --benchmark_out=/tmp/tmpBWKk0k -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:37:28 ------------------------------------------------------- -Benchmark Time CPU Iterations ------------------------------------------------------- -BM_memcpy/8 36 ns 36 ns 17891491 211.215MB/s -BM_memcpy/64 74 ns 74 ns 9400999 825.646MB/s -BM_memcpy/512 87 ns 87 ns 8027453 5.46126GB/s -BM_memcpy/1024 111 ns 111 ns 6116853 8.5648GB/s -BM_memcpy/8192 657 ns 656 ns 1064679 11.6247GB/s -RUNNING: ./a.out --benchmark_filter=BM_copy --benchmark_out=/tmp/tmpAvWcOM -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:37:33 ----------------------------------------------------- -Benchmark Time CPU Iterations ----------------------------------------------------- -BM_copy/8 227 ns 227 ns 3038700 33.6264MB/s -BM_copy/64 1640 ns 1640 ns 426893 37.2154MB/s -BM_copy/512 12804 ns 12801 ns 55417 38.1444MB/s -BM_copy/1024 25409 ns 25407 ns 27516 38.4365MB/s -BM_copy/8192 202986 ns 202990 ns 3454 38.4871MB/s -Comparing BM_memcpy to BM_copy (from ./a.out) -Benchmark Time CPU Time Old Time New CPU Old CPU New --------------------------------------------------------------------------------------------------------------------- -[BM_memcpy vs. BM_copy]/8 +5.2829 +5.2812 36 227 36 227 -[BM_memcpy vs. BM_copy]/64 +21.1719 +21.1856 74 1640 74 1640 -[BM_memcpy vs. BM_copy]/512 +145.6487 +145.6097 87 12804 87 12801 -[BM_memcpy vs. BM_copy]/1024 +227.1860 +227.1776 111 25409 111 25407 -[BM_memcpy vs. BM_copy]/8192 +308.1664 +308.2898 657 202986 656 202990 -``` - -As you can see, it applies filter to the benchmarks, both when running the benchmark, and before doing the diff. And to make the diff work, the matches are replaced with some common string. Thus, you can compare two different benchmark families within one benchmark binary. -As you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`. - -3. Compare filter one from benchmark one to filter two from benchmark two: -The program is invoked like: - -``` bash -$ compare.py filters [benchmark options]... -``` - -Where `` and `` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file. - -Where `` and `` are the same regex filters that you would pass to the `[--benchmark_filter=]` parameter of the benchmark binary. - -`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes. - -Example output: -``` -$ ./compare.py benchmarksfiltered ./a.out BM_memcpy ./a.out BM_copy -RUNNING: ./a.out --benchmark_filter=BM_memcpy --benchmark_out=/tmp/tmp_FvbYg -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:38:27 ------------------------------------------------------- -Benchmark Time CPU Iterations ------------------------------------------------------- -BM_memcpy/8 37 ns 37 ns 18953482 204.118MB/s -BM_memcpy/64 74 ns 74 ns 9206578 828.245MB/s -BM_memcpy/512 91 ns 91 ns 8086195 5.25476GB/s -BM_memcpy/1024 120 ns 120 ns 5804513 7.95662GB/s -BM_memcpy/8192 664 ns 664 ns 1028363 11.4948GB/s -RUNNING: ./a.out --benchmark_filter=BM_copy --benchmark_out=/tmp/tmpDfL5iE -Run on (8 X 4000 MHz CPU s) -2017-11-07 21:38:32 ----------------------------------------------------- -Benchmark Time CPU Iterations ----------------------------------------------------- -BM_copy/8 230 ns 230 ns 2985909 33.1161MB/s -BM_copy/64 1654 ns 1653 ns 419408 36.9137MB/s -BM_copy/512 13122 ns 13120 ns 53403 37.2156MB/s -BM_copy/1024 26679 ns 26666 ns 26575 36.6218MB/s -BM_copy/8192 215068 ns 215053 ns 3221 36.3283MB/s -Comparing BM_memcpy (from ./a.out) to BM_copy (from ./a.out) -Benchmark Time CPU Time Old Time New CPU Old CPU New --------------------------------------------------------------------------------------------------------------------- -[BM_memcpy vs. BM_copy]/8 +5.1649 +5.1637 37 230 37 230 -[BM_memcpy vs. BM_copy]/64 +21.4352 +21.4374 74 1654 74 1653 -[BM_memcpy vs. BM_copy]/512 +143.6022 +143.5865 91 13122 91 13120 -[BM_memcpy vs. BM_copy]/1024 +221.5903 +221.4790 120 26679 120 26666 -[BM_memcpy vs. BM_copy]/8192 +322.9059 +323.0096 664 215068 664 215053 -``` -This is a mix of the previous two modes, two (potentially different) benchmark binaries are run, and a different filter is applied to each one. -As you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`. - -### U test - -If there is a sufficient repetition count of the benchmarks, the tool can do -a [U Test](https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test), of the -null hypothesis that it is equally likely that a randomly selected value from -one sample will be less than or greater than a randomly selected value from a -second sample. - -If the calculated p-value is below this value is lower than the significance -level alpha, then the result is said to be statistically significant and the -null hypothesis is rejected. Which in other words means that the two benchmarks -aren't identical. - -**WARNING**: requires **LARGE** (no less than 9) number of repetitions to be -meaningful! diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/include/benchmark/benchmark.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/include/benchmark/benchmark.h deleted file mode 100644 index 6cb96f546d7..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/include/benchmark/benchmark.h +++ /dev/null @@ -1,1583 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Support for registering benchmarks for functions. - -/* Example usage: -// Define a function that executes the code to be measured a -// specified number of times: -static void BM_StringCreation(benchmark::State& state) { - for (auto _ : state) - std::string empty_string; -} - -// Register the function as a benchmark -BENCHMARK(BM_StringCreation); - -// Define another benchmark -static void BM_StringCopy(benchmark::State& state) { - std::string x = "hello"; - for (auto _ : state) - std::string copy(x); -} -BENCHMARK(BM_StringCopy); - -// Augment the main() program to invoke benchmarks if specified -// via the --benchmarks command line flag. E.g., -// my_unittest --benchmark_filter=all -// my_unittest --benchmark_filter=BM_StringCreation -// my_unittest --benchmark_filter=String -// my_unittest --benchmark_filter='Copy|Creation' -int main(int argc, char** argv) { - benchmark::Initialize(&argc, argv); - benchmark::RunSpecifiedBenchmarks(); - return 0; -} - -// Sometimes a family of microbenchmarks can be implemented with -// just one routine that takes an extra argument to specify which -// one of the family of benchmarks to run. For example, the following -// code defines a family of microbenchmarks for measuring the speed -// of memcpy() calls of different lengths: - -static void BM_memcpy(benchmark::State& state) { - char* src = new char[state.range(0)]; char* dst = new char[state.range(0)]; - memset(src, 'x', state.range(0)); - for (auto _ : state) - memcpy(dst, src, state.range(0)); - state.SetBytesProcessed(state.iterations() * state.range(0)); - delete[] src; delete[] dst; -} -BENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10); - -// The preceding code is quite repetitive, and can be replaced with the -// following short-hand. The following invocation will pick a few -// appropriate arguments in the specified range and will generate a -// microbenchmark for each such argument. -BENCHMARK(BM_memcpy)->Range(8, 8<<10); - -// You might have a microbenchmark that depends on two inputs. For -// example, the following code defines a family of microbenchmarks for -// measuring the speed of set insertion. -static void BM_SetInsert(benchmark::State& state) { - set data; - for (auto _ : state) { - state.PauseTiming(); - data = ConstructRandomSet(state.range(0)); - state.ResumeTiming(); - for (int j = 0; j < state.range(1); ++j) - data.insert(RandomNumber()); - } -} -BENCHMARK(BM_SetInsert) - ->Args({1<<10, 128}) - ->Args({2<<10, 128}) - ->Args({4<<10, 128}) - ->Args({8<<10, 128}) - ->Args({1<<10, 512}) - ->Args({2<<10, 512}) - ->Args({4<<10, 512}) - ->Args({8<<10, 512}); - -// The preceding code is quite repetitive, and can be replaced with -// the following short-hand. The following macro will pick a few -// appropriate arguments in the product of the two specified ranges -// and will generate a microbenchmark for each such pair. -BENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}}); - -// For more complex patterns of inputs, passing a custom function -// to Apply allows programmatic specification of an -// arbitrary set of arguments to run the microbenchmark on. -// The following example enumerates a dense range on -// one parameter, and a sparse range on the second. -static void CustomArguments(benchmark::internal::Benchmark* b) { - for (int i = 0; i <= 10; ++i) - for (int j = 32; j <= 1024*1024; j *= 8) - b->Args({i, j}); -} -BENCHMARK(BM_SetInsert)->Apply(CustomArguments); - -// Templated microbenchmarks work the same way: -// Produce then consume 'size' messages 'iters' times -// Measures throughput in the absence of multiprogramming. -template int BM_Sequential(benchmark::State& state) { - Q q; - typename Q::value_type v; - for (auto _ : state) { - for (int i = state.range(0); i--; ) - q.push(v); - for (int e = state.range(0); e--; ) - q.Wait(&v); - } - // actually messages, not bytes: - state.SetBytesProcessed(state.iterations() * state.range(0)); -} -BENCHMARK_TEMPLATE(BM_Sequential, WaitQueue)->Range(1<<0, 1<<10); - -Use `Benchmark::MinTime(double t)` to set the minimum time used to run the -benchmark. This option overrides the `benchmark_min_time` flag. - -void BM_test(benchmark::State& state) { - ... body ... -} -BENCHMARK(BM_test)->MinTime(2.0); // Run for at least 2 seconds. - -In a multithreaded test, it is guaranteed that none of the threads will start -until all have reached the loop start, and all will have finished before any -thread exits the loop body. As such, any global setup or teardown you want to -do can be wrapped in a check against the thread index: - -static void BM_MultiThreaded(benchmark::State& state) { - if (state.thread_index == 0) { - // Setup code here. - } - for (auto _ : state) { - // Run the test as normal. - } - if (state.thread_index == 0) { - // Teardown code here. - } -} -BENCHMARK(BM_MultiThreaded)->Threads(4); - - -If a benchmark runs a few milliseconds it may be hard to visually compare the -measured times, since the output data is given in nanoseconds per default. In -order to manually set the time unit, you can specify it manually: - -BENCHMARK(BM_test)->Unit(benchmark::kMillisecond); -*/ - -#ifndef BENCHMARK_BENCHMARK_H_ -#define BENCHMARK_BENCHMARK_H_ - -// The _MSVC_LANG check should detect Visual Studio 2015 Update 3 and newer. -#if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L) -#define BENCHMARK_HAS_CXX11 -#endif - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(BENCHMARK_HAS_CXX11) -#include -#include -#include -#endif - -#if defined(_MSC_VER) -#include // for _ReadWriteBarrier -#endif - -#ifndef BENCHMARK_HAS_CXX11 -#define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&); \ - TypeName& operator=(const TypeName&) -#else -#define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName&) = delete; \ - TypeName& operator=(const TypeName&) = delete -#endif - -#if defined(__GNUC__) -#define BENCHMARK_UNUSED __attribute__((unused)) -#define BENCHMARK_ALWAYS_INLINE __attribute__((always_inline)) -#define BENCHMARK_NOEXCEPT noexcept -#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) -#elif defined(_MSC_VER) && !defined(__clang__) -#define BENCHMARK_UNUSED -#define BENCHMARK_ALWAYS_INLINE __forceinline -#if _MSC_VER >= 1900 -#define BENCHMARK_NOEXCEPT noexcept -#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x) -#else -#define BENCHMARK_NOEXCEPT -#define BENCHMARK_NOEXCEPT_OP(x) -#endif -#define __func__ __FUNCTION__ -#else -#define BENCHMARK_UNUSED -#define BENCHMARK_ALWAYS_INLINE -#define BENCHMARK_NOEXCEPT -#define BENCHMARK_NOEXCEPT_OP(x) -#endif - -#define BENCHMARK_INTERNAL_TOSTRING2(x) #x -#define BENCHMARK_INTERNAL_TOSTRING(x) BENCHMARK_INTERNAL_TOSTRING2(x) - -#if defined(__GNUC__) || defined(__clang__) -#define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y) -#define BENCHMARK_DEPRECATED_MSG(msg) __attribute__((deprecated(msg))) -#else -#define BENCHMARK_BUILTIN_EXPECT(x, y) x -#define BENCHMARK_DEPRECATED_MSG(msg) -#define BENCHMARK_WARNING_MSG(msg) \ - __pragma(message(__FILE__ "(" BENCHMARK_INTERNAL_TOSTRING( \ - __LINE__) ") : warning note: " msg)) -#endif - -#if defined(__GNUC__) && !defined(__clang__) -#define BENCHMARK_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -#endif - -#ifndef __has_builtin -#define __has_builtin(x) 0 -#endif - -#if defined(__GNUC__) || __has_builtin(__builtin_unreachable) -#define BENCHMARK_UNREACHABLE() __builtin_unreachable() -#elif defined(_MSC_VER) -#define BENCHMARK_UNREACHABLE() __assume(false) -#else -#define BENCHMARK_UNREACHABLE() ((void)0) -#endif - -namespace benchmark { -class BenchmarkReporter; -class MemoryManager; - -void Initialize(int* argc, char** argv); - -// Report to stdout all arguments in 'argv' as unrecognized except the first. -// Returns true there is at least on unrecognized argument (i.e. 'argc' > 1). -bool ReportUnrecognizedArguments(int argc, char** argv); - -// Generate a list of benchmarks matching the specified --benchmark_filter flag -// and if --benchmark_list_tests is specified return after printing the name -// of each matching benchmark. Otherwise run each matching benchmark and -// report the results. -// -// The second and third overload use the specified 'display_reporter' and -// 'file_reporter' respectively. 'file_reporter' will write to the file -// specified -// by '--benchmark_output'. If '--benchmark_output' is not given the -// 'file_reporter' is ignored. -// -// RETURNS: The number of matching benchmarks. -size_t RunSpecifiedBenchmarks(); -size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter); -size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, - BenchmarkReporter* file_reporter); - -// Register a MemoryManager instance that will be used to collect and report -// allocation measurements for benchmark runs. -void RegisterMemoryManager(MemoryManager* memory_manager); - -namespace internal { -class Benchmark; -class BenchmarkImp; -class BenchmarkFamilies; - -void UseCharPointer(char const volatile*); - -// Take ownership of the pointer and register the benchmark. Return the -// registered benchmark. -Benchmark* RegisterBenchmarkInternal(Benchmark*); - -// Ensure that the standard streams are properly initialized in every TU. -int InitializeStreams(); -BENCHMARK_UNUSED static int stream_init_anchor = InitializeStreams(); - -} // namespace internal - -#if (!defined(__GNUC__) && !defined(__clang__)) || defined(__pnacl__) || \ - defined(__EMSCRIPTEN__) -#define BENCHMARK_HAS_NO_INLINE_ASSEMBLY -#endif - -// The DoNotOptimize(...) function can be used to prevent a value or -// expression from being optimized away by the compiler. This function is -// intended to add little to no overhead. -// See: https://youtu.be/nXaxk27zwlk?t=2441 -#ifndef BENCHMARK_HAS_NO_INLINE_ASSEMBLY -template -inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { - asm volatile("" : : "r,m"(value) : "memory"); -} - -template -inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) { -#if defined(__clang__) - asm volatile("" : "+r,m"(value) : : "memory"); -#else - asm volatile("" : "+m,r"(value) : : "memory"); -#endif -} - -// Force the compiler to flush pending writes to global memory. Acts as an -// effective read/write barrier -inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { - asm volatile("" : : : "memory"); -} -#elif defined(_MSC_VER) -template -inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { - internal::UseCharPointer(&reinterpret_cast(value)); - _ReadWriteBarrier(); -} - -inline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { _ReadWriteBarrier(); } -#else -template -inline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) { - internal::UseCharPointer(&reinterpret_cast(value)); -} -// FIXME Add ClobberMemory() for non-gnu and non-msvc compilers -#endif - -// This class is used for user-defined counters. -class Counter { - public: - enum Flags { - kDefaults = 0, - // Mark the counter as a rate. It will be presented divided - // by the duration of the benchmark. - kIsRate = 1U << 0U, - // Mark the counter as a thread-average quantity. It will be - // presented divided by the number of threads. - kAvgThreads = 1U << 1U, - // Mark the counter as a thread-average rate. See above. - kAvgThreadsRate = kIsRate | kAvgThreads, - // Mark the counter as a constant value, valid/same for *every* iteration. - // When reporting, it will be *multiplied* by the iteration count. - kIsIterationInvariant = 1U << 2U, - // Mark the counter as a constant rate. - // When reporting, it will be *multiplied* by the iteration count - // and then divided by the duration of the benchmark. - kIsIterationInvariantRate = kIsRate | kIsIterationInvariant, - // Mark the counter as a iteration-average quantity. - // It will be presented divided by the number of iterations. - kAvgIterations = 1U << 3U, - // Mark the counter as a iteration-average rate. See above. - kAvgIterationsRate = kIsRate | kAvgIterations - }; - - enum OneK { - // 1'000 items per 1k - kIs1000 = 1000, - // 1'024 items per 1k - kIs1024 = 1024 - }; - - double value; - Flags flags; - OneK oneK; - - BENCHMARK_ALWAYS_INLINE - Counter(double v = 0., Flags f = kDefaults, OneK k = kIs1000) - : value(v), flags(f), oneK(k) {} - - BENCHMARK_ALWAYS_INLINE operator double const&() const { return value; } - BENCHMARK_ALWAYS_INLINE operator double&() { return value; } -}; - -// A helper for user code to create unforeseen combinations of Flags, without -// having to do this cast manually each time, or providing this operator. -Counter::Flags inline operator|(const Counter::Flags& LHS, - const Counter::Flags& RHS) { - return static_cast(static_cast(LHS) | - static_cast(RHS)); -} - -// This is the container for the user-defined counters. -typedef std::map UserCounters; - -// TimeUnit is passed to a benchmark in order to specify the order of magnitude -// for the measured time. -enum TimeUnit { kNanosecond, kMicrosecond, kMillisecond }; - -// BigO is passed to a benchmark in order to specify the asymptotic -// computational -// complexity for the benchmark. In case oAuto is selected, complexity will be -// calculated automatically to the best fit. -enum BigO { oNone, o1, oN, oNSquared, oNCubed, oLogN, oNLogN, oAuto, oLambda }; - -typedef uint64_t IterationCount; - -// BigOFunc is passed to a benchmark in order to specify the asymptotic -// computational complexity for the benchmark. -typedef double(BigOFunc)(IterationCount); - -// StatisticsFunc is passed to a benchmark in order to compute some descriptive -// statistics over all the measurements of some type -typedef double(StatisticsFunc)(const std::vector&); - -namespace internal { -struct Statistics { - std::string name_; - StatisticsFunc* compute_; - - Statistics(const std::string& name, StatisticsFunc* compute) - : name_(name), compute_(compute) {} -}; - -struct BenchmarkInstance; -class ThreadTimer; -class ThreadManager; - -enum AggregationReportMode -#if defined(BENCHMARK_HAS_CXX11) - : unsigned -#else -#endif -{ - // The mode has not been manually specified - ARM_Unspecified = 0, - // The mode is user-specified. - // This may or may not be set when the following bit-flags are set. - ARM_Default = 1U << 0U, - // File reporter should only output aggregates. - ARM_FileReportAggregatesOnly = 1U << 1U, - // Display reporter should only output aggregates - ARM_DisplayReportAggregatesOnly = 1U << 2U, - // Both reporters should only display aggregates. - ARM_ReportAggregatesOnly = - ARM_FileReportAggregatesOnly | ARM_DisplayReportAggregatesOnly -}; - -} // namespace internal - -// State is passed to a running Benchmark and contains state for the -// benchmark to use. -class State { - public: - struct StateIterator; - friend struct StateIterator; - - // Returns iterators used to run each iteration of a benchmark using a - // C++11 ranged-based for loop. These functions should not be called directly. - // - // REQUIRES: The benchmark has not started running yet. Neither begin nor end - // have been called previously. - // - // NOTE: KeepRunning may not be used after calling either of these functions. - BENCHMARK_ALWAYS_INLINE StateIterator begin(); - BENCHMARK_ALWAYS_INLINE StateIterator end(); - - // Returns true if the benchmark should continue through another iteration. - // NOTE: A benchmark may not return from the test until KeepRunning() has - // returned false. - bool KeepRunning(); - - // Returns true iff the benchmark should run n more iterations. - // REQUIRES: 'n' > 0. - // NOTE: A benchmark must not return from the test until KeepRunningBatch() - // has returned false. - // NOTE: KeepRunningBatch() may overshoot by up to 'n' iterations. - // - // Intended usage: - // while (state.KeepRunningBatch(1000)) { - // // process 1000 elements - // } - bool KeepRunningBatch(IterationCount n); - - // REQUIRES: timer is running and 'SkipWithError(...)' has not been called - // by the current thread. - // Stop the benchmark timer. If not called, the timer will be - // automatically stopped after the last iteration of the benchmark loop. - // - // For threaded benchmarks the PauseTiming() function only pauses the timing - // for the current thread. - // - // NOTE: The "real time" measurement is per-thread. If different threads - // report different measurements the largest one is reported. - // - // NOTE: PauseTiming()/ResumeTiming() are relatively - // heavyweight, and so their use should generally be avoided - // within each benchmark iteration, if possible. - void PauseTiming(); - - // REQUIRES: timer is not running and 'SkipWithError(...)' has not been called - // by the current thread. - // Start the benchmark timer. The timer is NOT running on entrance to the - // benchmark function. It begins running after control flow enters the - // benchmark loop. - // - // NOTE: PauseTiming()/ResumeTiming() are relatively - // heavyweight, and so their use should generally be avoided - // within each benchmark iteration, if possible. - void ResumeTiming(); - - // REQUIRES: 'SkipWithError(...)' has not been called previously by the - // current thread. - // Report the benchmark as resulting in an error with the specified 'msg'. - // After this call the user may explicitly 'return' from the benchmark. - // - // If the ranged-for style of benchmark loop is used, the user must explicitly - // break from the loop, otherwise all future iterations will be run. - // If the 'KeepRunning()' loop is used the current thread will automatically - // exit the loop at the end of the current iteration. - // - // For threaded benchmarks only the current thread stops executing and future - // calls to `KeepRunning()` will block until all threads have completed - // the `KeepRunning()` loop. If multiple threads report an error only the - // first error message is used. - // - // NOTE: Calling 'SkipWithError(...)' does not cause the benchmark to exit - // the current scope immediately. If the function is called from within - // the 'KeepRunning()' loop the current iteration will finish. It is the users - // responsibility to exit the scope as needed. - void SkipWithError(const char* msg); - - // REQUIRES: called exactly once per iteration of the benchmarking loop. - // Set the manually measured time for this benchmark iteration, which - // is used instead of automatically measured time if UseManualTime() was - // specified. - // - // For threaded benchmarks the final value will be set to the largest - // reported values. - void SetIterationTime(double seconds); - - // Set the number of bytes processed by the current benchmark - // execution. This routine is typically called once at the end of a - // throughput oriented benchmark. - // - // REQUIRES: a benchmark has exited its benchmarking loop. - BENCHMARK_ALWAYS_INLINE - void SetBytesProcessed(int64_t bytes) { - counters["bytes_per_second"] = - Counter(static_cast(bytes), Counter::kIsRate, Counter::kIs1024); - } - - BENCHMARK_ALWAYS_INLINE - int64_t bytes_processed() const { - if (counters.find("bytes_per_second") != counters.end()) - return static_cast(counters.at("bytes_per_second")); - return 0; - } - - // If this routine is called with complexity_n > 0 and complexity report is - // requested for the - // family benchmark, then current benchmark will be part of the computation - // and complexity_n will - // represent the length of N. - BENCHMARK_ALWAYS_INLINE - void SetComplexityN(int64_t complexity_n) { complexity_n_ = complexity_n; } - - BENCHMARK_ALWAYS_INLINE - int64_t complexity_length_n() { return complexity_n_; } - - // If this routine is called with items > 0, then an items/s - // label is printed on the benchmark report line for the currently - // executing benchmark. It is typically called at the end of a processing - // benchmark where a processing items/second output is desired. - // - // REQUIRES: a benchmark has exited its benchmarking loop. - BENCHMARK_ALWAYS_INLINE - void SetItemsProcessed(int64_t items) { - counters["items_per_second"] = - Counter(static_cast(items), benchmark::Counter::kIsRate); - } - - BENCHMARK_ALWAYS_INLINE - int64_t items_processed() const { - if (counters.find("items_per_second") != counters.end()) - return static_cast(counters.at("items_per_second")); - return 0; - } - - // If this routine is called, the specified label is printed at the - // end of the benchmark report line for the currently executing - // benchmark. Example: - // static void BM_Compress(benchmark::State& state) { - // ... - // double compress = input_size / output_size; - // state.SetLabel(StrFormat("compress:%.1f%%", 100.0*compression)); - // } - // Produces output that looks like: - // BM_Compress 50 50 14115038 compress:27.3% - // - // REQUIRES: a benchmark has exited its benchmarking loop. - void SetLabel(const char* label); - - void BENCHMARK_ALWAYS_INLINE SetLabel(const std::string& str) { - this->SetLabel(str.c_str()); - } - - // Range arguments for this run. CHECKs if the argument has been set. - BENCHMARK_ALWAYS_INLINE - int64_t range(std::size_t pos = 0) const { - assert(range_.size() > pos); - return range_[pos]; - } - - BENCHMARK_DEPRECATED_MSG("use 'range(0)' instead") - int64_t range_x() const { return range(0); } - - BENCHMARK_DEPRECATED_MSG("use 'range(1)' instead") - int64_t range_y() const { return range(1); } - - BENCHMARK_ALWAYS_INLINE - IterationCount iterations() const { - if (BENCHMARK_BUILTIN_EXPECT(!started_, false)) { - return 0; - } - return max_iterations - total_iterations_ + batch_leftover_; - } - - private - : // items we expect on the first cache line (ie 64 bytes of the struct) - // When total_iterations_ is 0, KeepRunning() and friends will return false. - // May be larger than max_iterations. - IterationCount total_iterations_; - - // When using KeepRunningBatch(), batch_leftover_ holds the number of - // iterations beyond max_iters that were run. Used to track - // completed_iterations_ accurately. - IterationCount batch_leftover_; - - public: - const IterationCount max_iterations; - - private: - bool started_; - bool finished_; - bool error_occurred_; - - private: // items we don't need on the first cache line - std::vector range_; - - int64_t complexity_n_; - - public: - // Container for user-defined counters. - UserCounters counters; - // Index of the executing thread. Values from [0, threads). - const int thread_index; - // Number of threads concurrently executing the benchmark. - const int threads; - - private: - State(IterationCount max_iters, const std::vector& ranges, - int thread_i, int n_threads, internal::ThreadTimer* timer, - internal::ThreadManager* manager); - - void StartKeepRunning(); - // Implementation of KeepRunning() and KeepRunningBatch(). - // is_batch must be true unless n is 1. - bool KeepRunningInternal(IterationCount n, bool is_batch); - void FinishKeepRunning(); - internal::ThreadTimer* timer_; - internal::ThreadManager* manager_; - - friend struct internal::BenchmarkInstance; -}; - -inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunning() { - return KeepRunningInternal(1, /*is_batch=*/false); -} - -inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunningBatch(IterationCount n) { - return KeepRunningInternal(n, /*is_batch=*/true); -} - -inline BENCHMARK_ALWAYS_INLINE bool State::KeepRunningInternal(IterationCount n, - bool is_batch) { - // total_iterations_ is set to 0 by the constructor, and always set to a - // nonzero value by StartKepRunning(). - assert(n > 0); - // n must be 1 unless is_batch is true. - assert(is_batch || n == 1); - if (BENCHMARK_BUILTIN_EXPECT(total_iterations_ >= n, true)) { - total_iterations_ -= n; - return true; - } - if (!started_) { - StartKeepRunning(); - if (!error_occurred_ && total_iterations_ >= n) { - total_iterations_ -= n; - return true; - } - } - // For non-batch runs, total_iterations_ must be 0 by now. - if (is_batch && total_iterations_ != 0) { - batch_leftover_ = n - total_iterations_; - total_iterations_ = 0; - return true; - } - FinishKeepRunning(); - return false; -} - -struct State::StateIterator { - struct BENCHMARK_UNUSED Value {}; - typedef std::forward_iterator_tag iterator_category; - typedef Value value_type; - typedef Value reference; - typedef Value pointer; - typedef std::ptrdiff_t difference_type; - - private: - friend class State; - BENCHMARK_ALWAYS_INLINE - StateIterator() : cached_(0), parent_() {} - - BENCHMARK_ALWAYS_INLINE - explicit StateIterator(State* st) - : cached_(st->error_occurred_ ? 0 : st->max_iterations), parent_(st) {} - - public: - BENCHMARK_ALWAYS_INLINE - Value operator*() const { return Value(); } - - BENCHMARK_ALWAYS_INLINE - StateIterator& operator++() { - assert(cached_ > 0); - --cached_; - return *this; - } - - BENCHMARK_ALWAYS_INLINE - bool operator!=(StateIterator const&) const { - if (BENCHMARK_BUILTIN_EXPECT(cached_ != 0, true)) return true; - parent_->FinishKeepRunning(); - return false; - } - - private: - IterationCount cached_; - State* const parent_; -}; - -inline BENCHMARK_ALWAYS_INLINE State::StateIterator State::begin() { - return StateIterator(this); -} -inline BENCHMARK_ALWAYS_INLINE State::StateIterator State::end() { - StartKeepRunning(); - return StateIterator(); -} - -namespace internal { - -typedef void(Function)(State&); - -// ------------------------------------------------------ -// Benchmark registration object. The BENCHMARK() macro expands -// into an internal::Benchmark* object. Various methods can -// be called on this object to change the properties of the benchmark. -// Each method returns "this" so that multiple method calls can -// chained into one expression. -class Benchmark { - public: - virtual ~Benchmark(); - - // Note: the following methods all return "this" so that multiple - // method calls can be chained together in one expression. - - // Run this benchmark once with "x" as the extra argument passed - // to the function. - // REQUIRES: The function passed to the constructor must accept an arg1. - Benchmark* Arg(int64_t x); - - // Run this benchmark with the given time unit for the generated output report - Benchmark* Unit(TimeUnit unit); - - // Run this benchmark once for a number of values picked from the - // range [start..limit]. (start and limit are always picked.) - // REQUIRES: The function passed to the constructor must accept an arg1. - Benchmark* Range(int64_t start, int64_t limit); - - // Run this benchmark once for all values in the range [start..limit] with - // specific step - // REQUIRES: The function passed to the constructor must accept an arg1. - Benchmark* DenseRange(int64_t start, int64_t limit, int step = 1); - - // Run this benchmark once with "args" as the extra arguments passed - // to the function. - // REQUIRES: The function passed to the constructor must accept arg1, arg2 ... - Benchmark* Args(const std::vector& args); - - // Equivalent to Args({x, y}) - // NOTE: This is a legacy C++03 interface provided for compatibility only. - // New code should use 'Args'. - Benchmark* ArgPair(int64_t x, int64_t y) { - std::vector args; - args.push_back(x); - args.push_back(y); - return Args(args); - } - - // Run this benchmark once for a number of values picked from the - // ranges [start..limit]. (starts and limits are always picked.) - // REQUIRES: The function passed to the constructor must accept arg1, arg2 ... - Benchmark* Ranges(const std::vector >& ranges); - - // Equivalent to ArgNames({name}) - Benchmark* ArgName(const std::string& name); - - // Set the argument names to display in the benchmark name. If not called, - // only argument values will be shown. - Benchmark* ArgNames(const std::vector& names); - - // Equivalent to Ranges({{lo1, hi1}, {lo2, hi2}}). - // NOTE: This is a legacy C++03 interface provided for compatibility only. - // New code should use 'Ranges'. - Benchmark* RangePair(int64_t lo1, int64_t hi1, int64_t lo2, int64_t hi2) { - std::vector > ranges; - ranges.push_back(std::make_pair(lo1, hi1)); - ranges.push_back(std::make_pair(lo2, hi2)); - return Ranges(ranges); - } - - // Pass this benchmark object to *func, which can customize - // the benchmark by calling various methods like Arg, Args, - // Threads, etc. - Benchmark* Apply(void (*func)(Benchmark* benchmark)); - - // Set the range multiplier for non-dense range. If not called, the range - // multiplier kRangeMultiplier will be used. - Benchmark* RangeMultiplier(int multiplier); - - // Set the minimum amount of time to use when running this benchmark. This - // option overrides the `benchmark_min_time` flag. - // REQUIRES: `t > 0` and `Iterations` has not been called on this benchmark. - Benchmark* MinTime(double t); - - // Specify the amount of iterations that should be run by this benchmark. - // REQUIRES: 'n > 0' and `MinTime` has not been called on this benchmark. - // - // NOTE: This function should only be used when *exact* iteration control is - // needed and never to control or limit how long a benchmark runs, where - // `--benchmark_min_time=N` or `MinTime(...)` should be used instead. - Benchmark* Iterations(IterationCount n); - - // Specify the amount of times to repeat this benchmark. This option overrides - // the `benchmark_repetitions` flag. - // REQUIRES: `n > 0` - Benchmark* Repetitions(int n); - - // Specify if each repetition of the benchmark should be reported separately - // or if only the final statistics should be reported. If the benchmark - // is not repeated then the single result is always reported. - // Applies to *ALL* reporters (display and file). - Benchmark* ReportAggregatesOnly(bool value = true); - - // Same as ReportAggregatesOnly(), but applies to display reporter only. - Benchmark* DisplayAggregatesOnly(bool value = true); - - // By default, the CPU time is measured only for the main thread, which may - // be unrepresentative if the benchmark uses threads internally. If called, - // the total CPU time spent by all the threads will be measured instead. - // By default, the only the main thread CPU time will be measured. - Benchmark* MeasureProcessCPUTime(); - - // If a particular benchmark should use the Wall clock instead of the CPU time - // (be it either the CPU time of the main thread only (default), or the - // total CPU usage of the benchmark), call this method. If called, the elapsed - // (wall) time will be used to control how many iterations are run, and in the - // printing of items/second or MB/seconds values. - // If not called, the CPU time used by the benchmark will be used. - Benchmark* UseRealTime(); - - // If a benchmark must measure time manually (e.g. if GPU execution time is - // being - // measured), call this method. If called, each benchmark iteration should - // call - // SetIterationTime(seconds) to report the measured time, which will be used - // to control how many iterations are run, and in the printing of items/second - // or MB/second values. - Benchmark* UseManualTime(); - - // Set the asymptotic computational complexity for the benchmark. If called - // the asymptotic computational complexity will be shown on the output. - Benchmark* Complexity(BigO complexity = benchmark::oAuto); - - // Set the asymptotic computational complexity for the benchmark. If called - // the asymptotic computational complexity will be shown on the output. - Benchmark* Complexity(BigOFunc* complexity); - - // Add this statistics to be computed over all the values of benchmark run - Benchmark* ComputeStatistics(std::string name, StatisticsFunc* statistics); - - // Support for running multiple copies of the same benchmark concurrently - // in multiple threads. This may be useful when measuring the scaling - // of some piece of code. - - // Run one instance of this benchmark concurrently in t threads. - Benchmark* Threads(int t); - - // Pick a set of values T from [min_threads,max_threads]. - // min_threads and max_threads are always included in T. Run this - // benchmark once for each value in T. The benchmark run for a - // particular value t consists of t threads running the benchmark - // function concurrently. For example, consider: - // BENCHMARK(Foo)->ThreadRange(1,16); - // This will run the following benchmarks: - // Foo in 1 thread - // Foo in 2 threads - // Foo in 4 threads - // Foo in 8 threads - // Foo in 16 threads - Benchmark* ThreadRange(int min_threads, int max_threads); - - // For each value n in the range, run this benchmark once using n threads. - // min_threads and max_threads are always included in the range. - // stride specifies the increment. E.g. DenseThreadRange(1, 8, 3) starts - // a benchmark with 1, 4, 7 and 8 threads. - Benchmark* DenseThreadRange(int min_threads, int max_threads, int stride = 1); - - // Equivalent to ThreadRange(NumCPUs(), NumCPUs()) - Benchmark* ThreadPerCpu(); - - virtual void Run(State& state) = 0; - - protected: - explicit Benchmark(const char* name); - Benchmark(Benchmark const&); - void SetName(const char* name); - - int ArgsCnt() const; - - private: - friend class BenchmarkFamilies; - - std::string name_; - AggregationReportMode aggregation_report_mode_; - std::vector arg_names_; // Args for all benchmark runs - std::vector > args_; // Args for all benchmark runs - TimeUnit time_unit_; - int range_multiplier_; - double min_time_; - IterationCount iterations_; - int repetitions_; - bool measure_process_cpu_time_; - bool use_real_time_; - bool use_manual_time_; - BigO complexity_; - BigOFunc* complexity_lambda_; - std::vector statistics_; - std::vector thread_counts_; - - Benchmark& operator=(Benchmark const&); -}; - -} // namespace internal - -// Create and register a benchmark with the specified 'name' that invokes -// the specified functor 'fn'. -// -// RETURNS: A pointer to the registered benchmark. -internal::Benchmark* RegisterBenchmark(const char* name, - internal::Function* fn); - -#if defined(BENCHMARK_HAS_CXX11) -template -internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn); -#endif - -// Remove all registered benchmarks. All pointers to previously registered -// benchmarks are invalidated. -void ClearRegisteredBenchmarks(); - -namespace internal { -// The class used to hold all Benchmarks created from static function. -// (ie those created using the BENCHMARK(...) macros. -class FunctionBenchmark : public Benchmark { - public: - FunctionBenchmark(const char* name, Function* func) - : Benchmark(name), func_(func) {} - - virtual void Run(State& st); - - private: - Function* func_; -}; - -#ifdef BENCHMARK_HAS_CXX11 -template -class LambdaBenchmark : public Benchmark { - public: - virtual void Run(State& st) { lambda_(st); } - - private: - template - LambdaBenchmark(const char* name, OLambda&& lam) - : Benchmark(name), lambda_(std::forward(lam)) {} - - LambdaBenchmark(LambdaBenchmark const&) = delete; - - private: - template - friend Benchmark* ::benchmark::RegisterBenchmark(const char*, Lam&&); - - Lambda lambda_; -}; -#endif - -} // namespace internal - -inline internal::Benchmark* RegisterBenchmark(const char* name, - internal::Function* fn) { - return internal::RegisterBenchmarkInternal( - ::new internal::FunctionBenchmark(name, fn)); -} - -#ifdef BENCHMARK_HAS_CXX11 -template -internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn) { - using BenchType = - internal::LambdaBenchmark::type>; - return internal::RegisterBenchmarkInternal( - ::new BenchType(name, std::forward(fn))); -} -#endif - -#if defined(BENCHMARK_HAS_CXX11) && \ - (!defined(BENCHMARK_GCC_VERSION) || BENCHMARK_GCC_VERSION >= 409) -template -internal::Benchmark* RegisterBenchmark(const char* name, Lambda&& fn, - Args&&... args) { - return benchmark::RegisterBenchmark( - name, [=](benchmark::State& st) { fn(st, args...); }); -} -#else -#define BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK -#endif - -// The base class for all fixture tests. -class Fixture : public internal::Benchmark { - public: - Fixture() : internal::Benchmark("") {} - - virtual void Run(State& st) { - this->SetUp(st); - this->BenchmarkCase(st); - this->TearDown(st); - } - - // These will be deprecated ... - virtual void SetUp(const State&) {} - virtual void TearDown(const State&) {} - // ... In favor of these. - virtual void SetUp(State& st) { SetUp(const_cast(st)); } - virtual void TearDown(State& st) { TearDown(const_cast(st)); } - - protected: - virtual void BenchmarkCase(State&) = 0; -}; - -} // namespace benchmark - -// ------------------------------------------------------ -// Macro to register benchmarks - -// Check that __COUNTER__ is defined and that __COUNTER__ increases by 1 -// every time it is expanded. X + 1 == X + 0 is used in case X is defined to be -// empty. If X is empty the expression becomes (+1 == +0). -#if defined(__COUNTER__) && (__COUNTER__ + 1 == __COUNTER__ + 0) -#define BENCHMARK_PRIVATE_UNIQUE_ID __COUNTER__ -#else -#define BENCHMARK_PRIVATE_UNIQUE_ID __LINE__ -#endif - -// Helpers for generating unique variable names -#define BENCHMARK_PRIVATE_NAME(n) \ - BENCHMARK_PRIVATE_CONCAT(_benchmark_, BENCHMARK_PRIVATE_UNIQUE_ID, n) -#define BENCHMARK_PRIVATE_CONCAT(a, b, c) BENCHMARK_PRIVATE_CONCAT2(a, b, c) -#define BENCHMARK_PRIVATE_CONCAT2(a, b, c) a##b##c - -#define BENCHMARK_PRIVATE_DECLARE(n) \ - static ::benchmark::internal::Benchmark* BENCHMARK_PRIVATE_NAME(n) \ - BENCHMARK_UNUSED - -#define BENCHMARK(n) \ - BENCHMARK_PRIVATE_DECLARE(n) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark(#n, n))) - -// Old-style macros -#define BENCHMARK_WITH_ARG(n, a) BENCHMARK(n)->Arg((a)) -#define BENCHMARK_WITH_ARG2(n, a1, a2) BENCHMARK(n)->Args({(a1), (a2)}) -#define BENCHMARK_WITH_UNIT(n, t) BENCHMARK(n)->Unit((t)) -#define BENCHMARK_RANGE(n, lo, hi) BENCHMARK(n)->Range((lo), (hi)) -#define BENCHMARK_RANGE2(n, l1, h1, l2, h2) \ - BENCHMARK(n)->RangePair({{(l1), (h1)}, {(l2), (h2)}}) - -#ifdef BENCHMARK_HAS_CXX11 - -// Register a benchmark which invokes the function specified by `func` -// with the additional arguments specified by `...`. -// -// For example: -// -// template ` -// void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) { -// [...] -//} -// /* Registers a benchmark named "BM_takes_args/int_string_test` */ -// BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string("abc")); -#define BENCHMARK_CAPTURE(func, test_case_name, ...) \ - BENCHMARK_PRIVATE_DECLARE(func) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark( \ - #func "/" #test_case_name, \ - [](::benchmark::State& st) { func(st, __VA_ARGS__); }))) - -#endif // BENCHMARK_HAS_CXX11 - -// This will register a benchmark for a templatized function. For example: -// -// template -// void BM_Foo(int iters); -// -// BENCHMARK_TEMPLATE(BM_Foo, 1); -// -// will register BM_Foo<1> as a benchmark. -#define BENCHMARK_TEMPLATE1(n, a) \ - BENCHMARK_PRIVATE_DECLARE(n) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark(#n "<" #a ">", n))) - -#define BENCHMARK_TEMPLATE2(n, a, b) \ - BENCHMARK_PRIVATE_DECLARE(n) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark(#n "<" #a "," #b ">", \ - n))) - -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE(n, ...) \ - BENCHMARK_PRIVATE_DECLARE(n) = \ - (::benchmark::internal::RegisterBenchmarkInternal( \ - new ::benchmark::internal::FunctionBenchmark( \ - #n "<" #__VA_ARGS__ ">", n<__VA_ARGS__>))) -#else -#define BENCHMARK_TEMPLATE(n, a) BENCHMARK_TEMPLATE1(n, a) -#endif - -#define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ - class BaseClass##_##Method##_Benchmark : public BaseClass { \ - public: \ - BaseClass##_##Method##_Benchmark() : BaseClass() { \ - this->SetName(#BaseClass "/" #Method); \ - } \ - \ - protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ - }; - -#define BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ - class BaseClass##_##Method##_Benchmark : public BaseClass { \ - public: \ - BaseClass##_##Method##_Benchmark() : BaseClass() { \ - this->SetName(#BaseClass "<" #a ">/" #Method); \ - } \ - \ - protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ - }; - -#define BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ - class BaseClass##_##Method##_Benchmark : public BaseClass { \ - public: \ - BaseClass##_##Method##_Benchmark() : BaseClass() { \ - this->SetName(#BaseClass "<" #a "," #b ">/" #Method); \ - } \ - \ - protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ - }; - -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, ...) \ - class BaseClass##_##Method##_Benchmark : public BaseClass<__VA_ARGS__> { \ - public: \ - BaseClass##_##Method##_Benchmark() : BaseClass<__VA_ARGS__>() { \ - this->SetName(#BaseClass "<" #__VA_ARGS__ ">/" #Method); \ - } \ - \ - protected: \ - virtual void BenchmarkCase(::benchmark::State&); \ - }; -#else -#define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(n, a) \ - BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(n, a) -#endif - -#define BENCHMARK_DEFINE_F(BaseClass, Method) \ - BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#define BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a) \ - BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#define BENCHMARK_TEMPLATE2_DEFINE_F(BaseClass, Method, a, b) \ - BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, ...) \ - BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase -#else -#define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, a) \ - BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a) -#endif - -#define BENCHMARK_REGISTER_F(BaseClass, Method) \ - BENCHMARK_PRIVATE_REGISTER_F(BaseClass##_##Method##_Benchmark) - -#define BENCHMARK_PRIVATE_REGISTER_F(TestName) \ - BENCHMARK_PRIVATE_DECLARE(TestName) = \ - (::benchmark::internal::RegisterBenchmarkInternal(new TestName())) - -// This macro will define and register a benchmark within a fixture class. -#define BENCHMARK_F(BaseClass, Method) \ - BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \ - BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#define BENCHMARK_TEMPLATE1_F(BaseClass, Method, a) \ - BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \ - BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#define BENCHMARK_TEMPLATE2_F(BaseClass, Method, a, b) \ - BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \ - BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase - -#ifdef BENCHMARK_HAS_CXX11 -#define BENCHMARK_TEMPLATE_F(BaseClass, Method, ...) \ - BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \ - BENCHMARK_REGISTER_F(BaseClass, Method); \ - void BaseClass##_##Method##_Benchmark::BenchmarkCase -#else -#define BENCHMARK_TEMPLATE_F(BaseClass, Method, a) \ - BENCHMARK_TEMPLATE1_F(BaseClass, Method, a) -#endif - -// Helper macro to create a main routine in a test that runs the benchmarks -#define BENCHMARK_MAIN() \ - int main(int argc, char** argv) { \ - ::benchmark::Initialize(&argc, argv); \ - if (::benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; \ - ::benchmark::RunSpecifiedBenchmarks(); \ - } \ - int main(int, char**) - -// ------------------------------------------------------ -// Benchmark Reporters - -namespace benchmark { - -struct CPUInfo { - struct CacheInfo { - std::string type; - int level; - int size; - int num_sharing; - }; - - int num_cpus; - double cycles_per_second; - std::vector caches; - bool scaling_enabled; - std::vector load_avg; - - static const CPUInfo& Get(); - - private: - CPUInfo(); - BENCHMARK_DISALLOW_COPY_AND_ASSIGN(CPUInfo); -}; - -// Adding Struct for System Information -struct SystemInfo { - std::string name; - static const SystemInfo& Get(); - - private: - SystemInfo(); - BENCHMARK_DISALLOW_COPY_AND_ASSIGN(SystemInfo); -}; - -// BenchmarkName contains the components of the Benchmark's name -// which allows individual fields to be modified or cleared before -// building the final name using 'str()'. -struct BenchmarkName { - std::string function_name; - std::string args; - std::string min_time; - std::string iterations; - std::string repetitions; - std::string time_type; - std::string threads; - - // Return the full name of the benchmark with each non-empty - // field separated by a '/' - std::string str() const; -}; - -// Interface for custom benchmark result printers. -// By default, benchmark reports are printed to stdout. However an application -// can control the destination of the reports by calling -// RunSpecifiedBenchmarks and passing it a custom reporter object. -// The reporter object must implement the following interface. -class BenchmarkReporter { - public: - struct Context { - CPUInfo const& cpu_info; - SystemInfo const& sys_info; - // The number of chars in the longest benchmark name. - size_t name_field_width; - static const char* executable_name; - Context(); - }; - - struct Run { - static const int64_t no_repetition_index = -1; - enum RunType { RT_Iteration, RT_Aggregate }; - - Run() - : run_type(RT_Iteration), - error_occurred(false), - iterations(1), - threads(1), - time_unit(kNanosecond), - real_accumulated_time(0), - cpu_accumulated_time(0), - max_heapbytes_used(0), - complexity(oNone), - complexity_lambda(), - complexity_n(0), - report_big_o(false), - report_rms(false), - counters(), - has_memory_result(false), - allocs_per_iter(0.0), - max_bytes_used(0) {} - - std::string benchmark_name() const; - BenchmarkName run_name; - RunType run_type; - std::string aggregate_name; - std::string report_label; // Empty if not set by benchmark. - bool error_occurred; - std::string error_message; - - IterationCount iterations; - int64_t threads; - int64_t repetition_index; - int64_t repetitions; - TimeUnit time_unit; - double real_accumulated_time; - double cpu_accumulated_time; - - // Return a value representing the real time per iteration in the unit - // specified by 'time_unit'. - // NOTE: If 'iterations' is zero the returned value represents the - // accumulated time. - double GetAdjustedRealTime() const; - - // Return a value representing the cpu time per iteration in the unit - // specified by 'time_unit'. - // NOTE: If 'iterations' is zero the returned value represents the - // accumulated time. - double GetAdjustedCPUTime() const; - - // This is set to 0.0 if memory tracing is not enabled. - double max_heapbytes_used; - - // Keep track of arguments to compute asymptotic complexity - BigO complexity; - BigOFunc* complexity_lambda; - int64_t complexity_n; - - // what statistics to compute from the measurements - const std::vector* statistics; - - // Inform print function whether the current run is a complexity report - bool report_big_o; - bool report_rms; - - UserCounters counters; - - // Memory metrics. - bool has_memory_result; - double allocs_per_iter; - int64_t max_bytes_used; - }; - - // Construct a BenchmarkReporter with the output stream set to 'std::cout' - // and the error stream set to 'std::cerr' - BenchmarkReporter(); - - // Called once for every suite of benchmarks run. - // The parameter "context" contains information that the - // reporter may wish to use when generating its report, for example the - // platform under which the benchmarks are running. The benchmark run is - // never started if this function returns false, allowing the reporter - // to skip runs based on the context information. - virtual bool ReportContext(const Context& context) = 0; - - // Called once for each group of benchmark runs, gives information about - // cpu-time and heap memory usage during the benchmark run. If the group - // of runs contained more than two entries then 'report' contains additional - // elements representing the mean and standard deviation of those runs. - // Additionally if this group of runs was the last in a family of benchmarks - // 'reports' contains additional entries representing the asymptotic - // complexity and RMS of that benchmark family. - virtual void ReportRuns(const std::vector& report) = 0; - - // Called once and only once after ever group of benchmarks is run and - // reported. - virtual void Finalize() {} - - // REQUIRES: The object referenced by 'out' is valid for the lifetime - // of the reporter. - void SetOutputStream(std::ostream* out) { - assert(out); - output_stream_ = out; - } - - // REQUIRES: The object referenced by 'err' is valid for the lifetime - // of the reporter. - void SetErrorStream(std::ostream* err) { - assert(err); - error_stream_ = err; - } - - std::ostream& GetOutputStream() const { return *output_stream_; } - - std::ostream& GetErrorStream() const { return *error_stream_; } - - virtual ~BenchmarkReporter(); - - // Write a human readable string to 'out' representing the specified - // 'context'. - // REQUIRES: 'out' is non-null. - static void PrintBasicContext(std::ostream* out, Context const& context); - - private: - std::ostream* output_stream_; - std::ostream* error_stream_; -}; - -// Simple reporter that outputs benchmark data to the console. This is the -// default reporter used by RunSpecifiedBenchmarks(). -class ConsoleReporter : public BenchmarkReporter { - public: - enum OutputOptions { - OO_None = 0, - OO_Color = 1, - OO_Tabular = 2, - OO_ColorTabular = OO_Color | OO_Tabular, - OO_Defaults = OO_ColorTabular - }; - explicit ConsoleReporter(OutputOptions opts_ = OO_Defaults) - : output_options_(opts_), - name_field_width_(0), - prev_counters_(), - printed_header_(false) {} - - virtual bool ReportContext(const Context& context); - virtual void ReportRuns(const std::vector& reports); - - protected: - virtual void PrintRunData(const Run& report); - virtual void PrintHeader(const Run& report); - - OutputOptions output_options_; - size_t name_field_width_; - UserCounters prev_counters_; - bool printed_header_; -}; - -class JSONReporter : public BenchmarkReporter { - public: - JSONReporter() : first_report_(true) {} - virtual bool ReportContext(const Context& context); - virtual void ReportRuns(const std::vector& reports); - virtual void Finalize(); - - private: - void PrintRunData(const Run& report); - - bool first_report_; -}; - -class BENCHMARK_DEPRECATED_MSG( - "The CSV Reporter will be removed in a future release") CSVReporter - : public BenchmarkReporter { - public: - CSVReporter() : printed_header_(false) {} - virtual bool ReportContext(const Context& context); - virtual void ReportRuns(const std::vector& reports); - - private: - void PrintRunData(const Run& report); - - bool printed_header_; - std::set user_counter_names_; -}; - -// If a MemoryManager is registered, it can be used to collect and report -// allocation metrics for a run of the benchmark. -class MemoryManager { - public: - struct Result { - Result() : num_allocs(0), max_bytes_used(0) {} - - // The number of allocations made in total between Start and Stop. - int64_t num_allocs; - - // The peak memory use between Start and Stop. - int64_t max_bytes_used; - }; - - virtual ~MemoryManager() {} - - // Implement this to start recording allocation information. - virtual void Start() = 0; - - // Implement this to stop recording and fill out the given Result structure. - virtual void Stop(Result* result) = 0; -}; - -inline const char* GetTimeUnitString(TimeUnit unit) { - switch (unit) { - case kMillisecond: - return "ms"; - case kMicrosecond: - return "us"; - case kNanosecond: - return "ns"; - } - BENCHMARK_UNREACHABLE(); -} - -inline double GetTimeUnitMultiplier(TimeUnit unit) { - switch (unit) { - case kMillisecond: - return 1e3; - case kMicrosecond: - return 1e6; - case kNanosecond: - return 1e9; - } - BENCHMARK_UNREACHABLE(); -} - -} // namespace benchmark - -#endif // BENCHMARK_BENCHMARK_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/mingw.py b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/mingw.py deleted file mode 100644 index 706ad559db9..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/mingw.py +++ /dev/null @@ -1,320 +0,0 @@ -#! /usr/bin/env python -# encoding: utf-8 - -import argparse -import errno -import logging -import os -import platform -import re -import sys -import subprocess -import tempfile - -try: - import winreg -except ImportError: - import _winreg as winreg -try: - import urllib.request as request -except ImportError: - import urllib as request -try: - import urllib.parse as parse -except ImportError: - import urlparse as parse - -class EmptyLogger(object): - ''' - Provides an implementation that performs no logging - ''' - def debug(self, *k, **kw): - pass - def info(self, *k, **kw): - pass - def warn(self, *k, **kw): - pass - def error(self, *k, **kw): - pass - def critical(self, *k, **kw): - pass - def setLevel(self, *k, **kw): - pass - -urls = ( - 'http://downloads.sourceforge.net/project/mingw-w64/Toolchains%20' - 'targetting%20Win32/Personal%20Builds/mingw-builds/installer/' - 'repository.txt', - 'http://downloads.sourceforge.net/project/mingwbuilds/host-windows/' - 'repository.txt' -) -''' -A list of mingw-build repositories -''' - -def repository(urls = urls, log = EmptyLogger()): - ''' - Downloads and parse mingw-build repository files and parses them - ''' - log.info('getting mingw-builds repository') - versions = {} - re_sourceforge = re.compile(r'http://sourceforge.net/projects/([^/]+)/files') - re_sub = r'http://downloads.sourceforge.net/project/\1' - for url in urls: - log.debug(' - requesting: %s', url) - socket = request.urlopen(url) - repo = socket.read() - if not isinstance(repo, str): - repo = repo.decode(); - socket.close() - for entry in repo.split('\n')[:-1]: - value = entry.split('|') - version = tuple([int(n) for n in value[0].strip().split('.')]) - version = versions.setdefault(version, {}) - arch = value[1].strip() - if arch == 'x32': - arch = 'i686' - elif arch == 'x64': - arch = 'x86_64' - arch = version.setdefault(arch, {}) - threading = arch.setdefault(value[2].strip(), {}) - exceptions = threading.setdefault(value[3].strip(), {}) - revision = exceptions.setdefault(int(value[4].strip()[3:]), - re_sourceforge.sub(re_sub, value[5].strip())) - return versions - -def find_in_path(file, path=None): - ''' - Attempts to find an executable in the path - ''' - if platform.system() == 'Windows': - file += '.exe' - if path is None: - path = os.environ.get('PATH', '') - if type(path) is type(''): - path = path.split(os.pathsep) - return list(filter(os.path.exists, - map(lambda dir, file=file: os.path.join(dir, file), path))) - -def find_7zip(log = EmptyLogger()): - ''' - Attempts to find 7zip for unpacking the mingw-build archives - ''' - log.info('finding 7zip') - path = find_in_path('7z') - if not path: - key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\7-Zip') - path, _ = winreg.QueryValueEx(key, 'Path') - path = [os.path.join(path, '7z.exe')] - log.debug('found \'%s\'', path[0]) - return path[0] - -find_7zip() - -def unpack(archive, location, log = EmptyLogger()): - ''' - Unpacks a mingw-builds archive - ''' - sevenzip = find_7zip(log) - log.info('unpacking %s', os.path.basename(archive)) - cmd = [sevenzip, 'x', archive, '-o' + location, '-y'] - log.debug(' - %r', cmd) - with open(os.devnull, 'w') as devnull: - subprocess.check_call(cmd, stdout = devnull) - -def download(url, location, log = EmptyLogger()): - ''' - Downloads and unpacks a mingw-builds archive - ''' - log.info('downloading MinGW') - log.debug(' - url: %s', url) - log.debug(' - location: %s', location) - - re_content = re.compile(r'attachment;[ \t]*filename=(")?([^"]*)(")?[\r\n]*') - - stream = request.urlopen(url) - try: - content = stream.getheader('Content-Disposition') or '' - except AttributeError: - content = stream.headers.getheader('Content-Disposition') or '' - matches = re_content.match(content) - if matches: - filename = matches.group(2) - else: - parsed = parse.urlparse(stream.geturl()) - filename = os.path.basename(parsed.path) - - try: - os.makedirs(location) - except OSError as e: - if e.errno == errno.EEXIST and os.path.isdir(location): - pass - else: - raise - - archive = os.path.join(location, filename) - with open(archive, 'wb') as out: - while True: - buf = stream.read(1024) - if not buf: - break - out.write(buf) - unpack(archive, location, log = log) - os.remove(archive) - - possible = os.path.join(location, 'mingw64') - if not os.path.exists(possible): - possible = os.path.join(location, 'mingw32') - if not os.path.exists(possible): - raise ValueError('Failed to find unpacked MinGW: ' + possible) - return possible - -def root(location = None, arch = None, version = None, threading = None, - exceptions = None, revision = None, log = EmptyLogger()): - ''' - Returns the root folder of a specific version of the mingw-builds variant - of gcc. Will download the compiler if needed - ''' - - # Get the repository if we don't have all the information - if not (arch and version and threading and exceptions and revision): - versions = repository(log = log) - - # Determine some defaults - version = version or max(versions.keys()) - if not arch: - arch = platform.machine().lower() - if arch == 'x86': - arch = 'i686' - elif arch == 'amd64': - arch = 'x86_64' - if not threading: - keys = versions[version][arch].keys() - if 'posix' in keys: - threading = 'posix' - elif 'win32' in keys: - threading = 'win32' - else: - threading = keys[0] - if not exceptions: - keys = versions[version][arch][threading].keys() - if 'seh' in keys: - exceptions = 'seh' - elif 'sjlj' in keys: - exceptions = 'sjlj' - else: - exceptions = keys[0] - if revision == None: - revision = max(versions[version][arch][threading][exceptions].keys()) - if not location: - location = os.path.join(tempfile.gettempdir(), 'mingw-builds') - - # Get the download url - url = versions[version][arch][threading][exceptions][revision] - - # Tell the user whatzzup - log.info('finding MinGW %s', '.'.join(str(v) for v in version)) - log.debug(' - arch: %s', arch) - log.debug(' - threading: %s', threading) - log.debug(' - exceptions: %s', exceptions) - log.debug(' - revision: %s', revision) - log.debug(' - url: %s', url) - - # Store each specific revision differently - slug = '{version}-{arch}-{threading}-{exceptions}-rev{revision}' - slug = slug.format( - version = '.'.join(str(v) for v in version), - arch = arch, - threading = threading, - exceptions = exceptions, - revision = revision - ) - if arch == 'x86_64': - root_dir = os.path.join(location, slug, 'mingw64') - elif arch == 'i686': - root_dir = os.path.join(location, slug, 'mingw32') - else: - raise ValueError('Unknown MinGW arch: ' + arch) - - # Download if needed - if not os.path.exists(root_dir): - downloaded = download(url, os.path.join(location, slug), log = log) - if downloaded != root_dir: - raise ValueError('The location of mingw did not match\n%s\n%s' - % (downloaded, root_dir)) - - return root_dir - -def str2ver(string): - ''' - Converts a version string into a tuple - ''' - try: - version = tuple(int(v) for v in string.split('.')) - if len(version) is not 3: - raise ValueError() - except ValueError: - raise argparse.ArgumentTypeError( - 'please provide a three digit version string') - return version - -def main(): - ''' - Invoked when the script is run directly by the python interpreter - ''' - parser = argparse.ArgumentParser( - description = 'Downloads a specific version of MinGW', - formatter_class = argparse.ArgumentDefaultsHelpFormatter - ) - parser.add_argument('--location', - help = 'the location to download the compiler to', - default = os.path.join(tempfile.gettempdir(), 'mingw-builds')) - parser.add_argument('--arch', required = True, choices = ['i686', 'x86_64'], - help = 'the target MinGW architecture string') - parser.add_argument('--version', type = str2ver, - help = 'the version of GCC to download') - parser.add_argument('--threading', choices = ['posix', 'win32'], - help = 'the threading type of the compiler') - parser.add_argument('--exceptions', choices = ['sjlj', 'seh', 'dwarf'], - help = 'the method to throw exceptions') - parser.add_argument('--revision', type=int, - help = 'the revision of the MinGW release') - group = parser.add_mutually_exclusive_group() - group.add_argument('-v', '--verbose', action='store_true', - help='increase the script output verbosity') - group.add_argument('-q', '--quiet', action='store_true', - help='only print errors and warning') - args = parser.parse_args() - - # Create the logger - logger = logging.getLogger('mingw') - handler = logging.StreamHandler() - formatter = logging.Formatter('%(message)s') - handler.setFormatter(formatter) - logger.addHandler(handler) - logger.setLevel(logging.INFO) - if args.quiet: - logger.setLevel(logging.WARN) - if args.verbose: - logger.setLevel(logging.DEBUG) - - # Get MinGW - root_dir = root(location = args.location, arch = args.arch, - version = args.version, threading = args.threading, - exceptions = args.exceptions, revision = args.revision, - log = logger) - - sys.stdout.write('%s\n' % os.path.join(root_dir, 'bin')) - -if __name__ == '__main__': - try: - main() - except IOError as e: - sys.stderr.write('IO error: %s\n' % e) - sys.exit(1) - except OSError as e: - sys.stderr.write('OS error: %s\n' % e) - sys.exit(1) - except KeyboardInterrupt as e: - sys.stderr.write('Killed\n') - sys.exit(1) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/releasing.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/releasing.md deleted file mode 100644 index f0cd7010e3a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/releasing.md +++ /dev/null @@ -1,16 +0,0 @@ -# How to release - -* Make sure you're on master and synced to HEAD -* Ensure the project builds and tests run (sanity check only, obviously) - * `parallel -j0 exec ::: test/*_test` can help ensure everything at least - passes -* Prepare release notes - * `git log $(git describe --abbrev=0 --tags)..HEAD` gives you the list of - commits between the last annotated tag and HEAD - * Pick the most interesting. -* Create a release through github's interface - * Note this will create a lightweight tag. - * Update this to an annotated tag: - * `git pull --tags` - * `git tag -a -f ` - * `git push --force origin` diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/CMakeLists.txt b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/CMakeLists.txt deleted file mode 100644 index b47de6791cc..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/CMakeLists.txt +++ /dev/null @@ -1,112 +0,0 @@ -# Allow the source files to find headers in src/ -include(GNUInstallDirs) -include_directories(${PROJECT_SOURCE_DIR}/src) - -if (DEFINED BENCHMARK_CXX_LINKER_FLAGS) - list(APPEND CMAKE_SHARED_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) - list(APPEND CMAKE_MODULE_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) -endif() - -file(GLOB - SOURCE_FILES - *.cc - ${PROJECT_SOURCE_DIR}/include/benchmark/*.h - ${CMAKE_CURRENT_SOURCE_DIR}/*.h) -file(GLOB BENCHMARK_MAIN "benchmark_main.cc") -foreach(item ${BENCHMARK_MAIN}) - list(REMOVE_ITEM SOURCE_FILES "${item}") -endforeach() - -add_library(benchmark ${SOURCE_FILES}) -set_target_properties(benchmark PROPERTIES - OUTPUT_NAME "benchmark" - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) -target_include_directories(benchmark PUBLIC - $ - ) - -# Link threads. -target_link_libraries(benchmark ${BENCHMARK_CXX_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) -find_library(LIBRT rt) -if(LIBRT) - target_link_libraries(benchmark ${LIBRT}) -endif() - -if(CMAKE_BUILD_TYPE) - string(TOUPPER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_UPPER) -endif() -if(NOT CMAKE_THREAD_LIBS_INIT AND "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE_UPPER}}" MATCHES ".*-fsanitize=[^ ]*address.*") - message(WARNING "CMake's FindThreads.cmake did not fail, but CMAKE_THREAD_LIBS_INIT ended up being empty. This was fixed in https://github.com/Kitware/CMake/commit/d53317130e84898c5328c237186dbd995aaf1c12 Let's guess that -pthread is sufficient.") - target_link_libraries(benchmark -pthread) -endif() - -# We need extra libraries on Windows -if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - target_link_libraries(benchmark Shlwapi) -endif() - -# We need extra libraries on Solaris -if(${CMAKE_SYSTEM_NAME} MATCHES "SunOS") - target_link_libraries(benchmark kstat) -endif() - -# Benchmark main library -add_library(benchmark_main "benchmark_main.cc") -set_target_properties(benchmark_main PROPERTIES - OUTPUT_NAME "benchmark_main" - VERSION ${GENERIC_LIB_VERSION} - SOVERSION ${GENERIC_LIB_SOVERSION} -) -target_include_directories(benchmark PUBLIC - $ - ) -target_link_libraries(benchmark_main benchmark) - - -set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated") - -set(version_config "${generated_dir}/${PROJECT_NAME}ConfigVersion.cmake") -set(project_config "${generated_dir}/${PROJECT_NAME}Config.cmake") -set(pkg_config "${generated_dir}/${PROJECT_NAME}.pc") -set(targets_export_name "${PROJECT_NAME}Targets") - -set(namespace "${PROJECT_NAME}::") - -include(CMakePackageConfigHelpers) -write_basic_package_version_file( - "${version_config}" VERSION ${GENERIC_LIB_VERSION} COMPATIBILITY SameMajorVersion -) - -configure_file("${PROJECT_SOURCE_DIR}/cmake/Config.cmake.in" "${project_config}" @ONLY) -configure_file("${PROJECT_SOURCE_DIR}/cmake/benchmark.pc.in" "${pkg_config}" @ONLY) - -if (BENCHMARK_ENABLE_INSTALL) - # Install target (will install the library to specified CMAKE_INSTALL_PREFIX variable) - install( - TARGETS benchmark benchmark_main - EXPORT ${targets_export_name} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) - - install( - DIRECTORY "${PROJECT_SOURCE_DIR}/include/benchmark" - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} - FILES_MATCHING PATTERN "*.*h") - - install( - FILES "${project_config}" "${version_config}" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") - - install( - FILES "${pkg_config}" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") - - install( - EXPORT "${targets_export_name}" - NAMESPACE "${namespace}" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") -endif() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/arraysize.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/arraysize.h deleted file mode 100644 index 51a50f2dff2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/arraysize.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef BENCHMARK_ARRAYSIZE_H_ -#define BENCHMARK_ARRAYSIZE_H_ - -#include "internal_macros.h" - -namespace benchmark { -namespace internal { -// The arraysize(arr) macro returns the # of elements in an array arr. -// The expression is a compile-time constant, and therefore can be -// used in defining new arrays, for example. If you use arraysize on -// a pointer by mistake, you will get a compile-time error. -// - -// This template function declaration is used in defining arraysize. -// Note that the function doesn't need an implementation, as we only -// use its type. -template -char (&ArraySizeHelper(T (&array)[N]))[N]; - -// That gcc wants both of these prototypes seems mysterious. VC, for -// its part, can't decide which to use (another mystery). Matching of -// template overloads: the final frontier. -#ifndef COMPILER_MSVC -template -char (&ArraySizeHelper(const T (&array)[N]))[N]; -#endif - -#define arraysize(array) (sizeof(::benchmark::internal::ArraySizeHelper(array))) - -} // end namespace internal -} // end namespace benchmark - -#endif // BENCHMARK_ARRAYSIZE_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark.cc deleted file mode 100644 index 29bfa3512f9..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark.cc +++ /dev/null @@ -1,494 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "benchmark_api_internal.h" -#include "benchmark_runner.h" -#include "internal_macros.h" - -#ifndef BENCHMARK_OS_WINDOWS -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "colorprint.h" -#include "commandlineflags.h" -#include "complexity.h" -#include "counter.h" -#include "internal_macros.h" -#include "log.h" -#include "mutex.h" -#include "re.h" -#include "statistics.h" -#include "string_util.h" -#include "thread_manager.h" -#include "thread_timer.h" - -DEFINE_bool(benchmark_list_tests, false, - "Print a list of benchmarks. This option overrides all other " - "options."); - -DEFINE_string(benchmark_filter, ".", - "A regular expression that specifies the set of benchmarks " - "to execute. If this flag is empty, or if this flag is the " - "string \"all\", all benchmarks linked into the binary are " - "run."); - -DEFINE_double(benchmark_min_time, 0.5, - "Minimum number of seconds we should run benchmark before " - "results are considered significant. For cpu-time based " - "tests, this is the lower bound on the total cpu time " - "used by all threads that make up the test. For real-time " - "based tests, this is the lower bound on the elapsed time " - "of the benchmark execution, regardless of number of " - "threads."); - -DEFINE_int32(benchmark_repetitions, 1, - "The number of runs of each benchmark. If greater than 1, the " - "mean and standard deviation of the runs will be reported."); - -DEFINE_bool( - benchmark_report_aggregates_only, false, - "Report the result of each benchmark repetitions. When 'true' is specified " - "only the mean, standard deviation, and other statistics are reported for " - "repeated benchmarks. Affects all reporters."); - -DEFINE_bool( - benchmark_display_aggregates_only, false, - "Display the result of each benchmark repetitions. When 'true' is " - "specified only the mean, standard deviation, and other statistics are " - "displayed for repeated benchmarks. Unlike " - "benchmark_report_aggregates_only, only affects the display reporter, but " - "*NOT* file reporter, which will still contain all the output."); - -DEFINE_string(benchmark_format, "console", - "The format to use for console output. Valid values are " - "'console', 'json', or 'csv'."); - -DEFINE_string(benchmark_out_format, "json", - "The format to use for file output. Valid values are " - "'console', 'json', or 'csv'."); - -DEFINE_string(benchmark_out, "", "The file to write additional output to"); - -DEFINE_string(benchmark_color, "auto", - "Whether to use colors in the output. Valid values: " - "'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use " - "colors if the output is being sent to a terminal and the TERM " - "environment variable is set to a terminal type that supports " - "colors."); - -DEFINE_bool(benchmark_counters_tabular, false, - "Whether to use tabular format when printing user counters to " - "the console. Valid values: 'true'/'yes'/1, 'false'/'no'/0." - "Defaults to false."); - -DEFINE_int32(v, 0, "The level of verbose logging to output"); - -namespace benchmark { - -namespace internal { - -// FIXME: wouldn't LTO mess this up? -void UseCharPointer(char const volatile*) {} - -} // namespace internal - -State::State(IterationCount max_iters, const std::vector& ranges, - int thread_i, int n_threads, internal::ThreadTimer* timer, - internal::ThreadManager* manager) - : total_iterations_(0), - batch_leftover_(0), - max_iterations(max_iters), - started_(false), - finished_(false), - error_occurred_(false), - range_(ranges), - complexity_n_(0), - counters(), - thread_index(thread_i), - threads(n_threads), - timer_(timer), - manager_(manager) { - CHECK(max_iterations != 0) << "At least one iteration must be run"; - CHECK_LT(thread_index, threads) << "thread_index must be less than threads"; - - // Note: The use of offsetof below is technically undefined until C++17 - // because State is not a standard layout type. However, all compilers - // currently provide well-defined behavior as an extension (which is - // demonstrated since constexpr evaluation must diagnose all undefined - // behavior). However, GCC and Clang also warn about this use of offsetof, - // which must be suppressed. -#if defined(__INTEL_COMPILER) -#pragma warning push -#pragma warning(disable:1875) -#elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Winvalid-offsetof" -#endif - // Offset tests to ensure commonly accessed data is on the first cache line. - const int cache_line_size = 64; - static_assert(offsetof(State, error_occurred_) <= - (cache_line_size - sizeof(error_occurred_)), - ""); -#if defined(__INTEL_COMPILER) -#pragma warning pop -#elif defined(__GNUC__) -#pragma GCC diagnostic pop -#endif -} - -void State::PauseTiming() { - // Add in time accumulated so far - CHECK(started_ && !finished_ && !error_occurred_); - timer_->StopTimer(); -} - -void State::ResumeTiming() { - CHECK(started_ && !finished_ && !error_occurred_); - timer_->StartTimer(); -} - -void State::SkipWithError(const char* msg) { - CHECK(msg); - error_occurred_ = true; - { - MutexLock l(manager_->GetBenchmarkMutex()); - if (manager_->results.has_error_ == false) { - manager_->results.error_message_ = msg; - manager_->results.has_error_ = true; - } - } - total_iterations_ = 0; - if (timer_->running()) timer_->StopTimer(); -} - -void State::SetIterationTime(double seconds) { - timer_->SetIterationTime(seconds); -} - -void State::SetLabel(const char* label) { - MutexLock l(manager_->GetBenchmarkMutex()); - manager_->results.report_label_ = label; -} - -void State::StartKeepRunning() { - CHECK(!started_ && !finished_); - started_ = true; - total_iterations_ = error_occurred_ ? 0 : max_iterations; - manager_->StartStopBarrier(); - if (!error_occurred_) ResumeTiming(); -} - -void State::FinishKeepRunning() { - CHECK(started_ && (!finished_ || error_occurred_)); - if (!error_occurred_) { - PauseTiming(); - } - // Total iterations has now wrapped around past 0. Fix this. - total_iterations_ = 0; - finished_ = true; - manager_->StartStopBarrier(); -} - -namespace internal { -namespace { - -void RunBenchmarks(const std::vector& benchmarks, - BenchmarkReporter* display_reporter, - BenchmarkReporter* file_reporter) { - // Note the file_reporter can be null. - CHECK(display_reporter != nullptr); - - // Determine the width of the name field using a minimum width of 10. - bool might_have_aggregates = FLAGS_benchmark_repetitions > 1; - size_t name_field_width = 10; - size_t stat_field_width = 0; - for (const BenchmarkInstance& benchmark : benchmarks) { - name_field_width = - std::max(name_field_width, benchmark.name.str().size()); - might_have_aggregates |= benchmark.repetitions > 1; - - for (const auto& Stat : *benchmark.statistics) - stat_field_width = std::max(stat_field_width, Stat.name_.size()); - } - if (might_have_aggregates) name_field_width += 1 + stat_field_width; - - // Print header here - BenchmarkReporter::Context context; - context.name_field_width = name_field_width; - - // Keep track of running times of all instances of current benchmark - std::vector complexity_reports; - - // We flush streams after invoking reporter methods that write to them. This - // ensures users get timely updates even when streams are not line-buffered. - auto flushStreams = [](BenchmarkReporter* reporter) { - if (!reporter) return; - std::flush(reporter->GetOutputStream()); - std::flush(reporter->GetErrorStream()); - }; - - if (display_reporter->ReportContext(context) && - (!file_reporter || file_reporter->ReportContext(context))) { - flushStreams(display_reporter); - flushStreams(file_reporter); - - for (const auto& benchmark : benchmarks) { - RunResults run_results = RunBenchmark(benchmark, &complexity_reports); - - auto report = [&run_results](BenchmarkReporter* reporter, - bool report_aggregates_only) { - assert(reporter); - // If there are no aggregates, do output non-aggregates. - report_aggregates_only &= !run_results.aggregates_only.empty(); - if (!report_aggregates_only) - reporter->ReportRuns(run_results.non_aggregates); - if (!run_results.aggregates_only.empty()) - reporter->ReportRuns(run_results.aggregates_only); - }; - - report(display_reporter, run_results.display_report_aggregates_only); - if (file_reporter) - report(file_reporter, run_results.file_report_aggregates_only); - - flushStreams(display_reporter); - flushStreams(file_reporter); - } - } - display_reporter->Finalize(); - if (file_reporter) file_reporter->Finalize(); - flushStreams(display_reporter); - flushStreams(file_reporter); -} - -std::unique_ptr CreateReporter( - std::string const& name, ConsoleReporter::OutputOptions output_opts) { - typedef std::unique_ptr PtrType; - if (name == "console") { - return PtrType(new ConsoleReporter(output_opts)); - } else if (name == "json") { - return PtrType(new JSONReporter); - } else if (name == "csv") { - return PtrType(new CSVReporter); - } else { - std::cerr << "Unexpected format: '" << name << "'\n"; - std::exit(1); - } -} - -} // end namespace - -bool IsZero(double n) { - return std::abs(n) < std::numeric_limits::epsilon(); -} - -ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) { - int output_opts = ConsoleReporter::OO_Defaults; - auto is_benchmark_color = [force_no_color] () -> bool { - if (force_no_color) { - return false; - } - if (FLAGS_benchmark_color == "auto") { - return IsColorTerminal(); - } - return IsTruthyFlagValue(FLAGS_benchmark_color); - }; - if (is_benchmark_color()) { - output_opts |= ConsoleReporter::OO_Color; - } else { - output_opts &= ~ConsoleReporter::OO_Color; - } - if (FLAGS_benchmark_counters_tabular) { - output_opts |= ConsoleReporter::OO_Tabular; - } else { - output_opts &= ~ConsoleReporter::OO_Tabular; - } - return static_cast(output_opts); -} - -} // end namespace internal - -size_t RunSpecifiedBenchmarks() { - return RunSpecifiedBenchmarks(nullptr, nullptr); -} - -size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter) { - return RunSpecifiedBenchmarks(display_reporter, nullptr); -} - -size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, - BenchmarkReporter* file_reporter) { - std::string spec = FLAGS_benchmark_filter; - if (spec.empty() || spec == "all") - spec = "."; // Regexp that matches all benchmarks - - // Setup the reporters - std::ofstream output_file; - std::unique_ptr default_display_reporter; - std::unique_ptr default_file_reporter; - if (!display_reporter) { - default_display_reporter = internal::CreateReporter( - FLAGS_benchmark_format, internal::GetOutputOptions()); - display_reporter = default_display_reporter.get(); - } - auto& Out = display_reporter->GetOutputStream(); - auto& Err = display_reporter->GetErrorStream(); - - std::string const& fname = FLAGS_benchmark_out; - if (fname.empty() && file_reporter) { - Err << "A custom file reporter was provided but " - "--benchmark_out= was not specified." - << std::endl; - std::exit(1); - } - if (!fname.empty()) { - output_file.open(fname); - if (!output_file.is_open()) { - Err << "invalid file name: '" << fname << std::endl; - std::exit(1); - } - if (!file_reporter) { - default_file_reporter = internal::CreateReporter( - FLAGS_benchmark_out_format, ConsoleReporter::OO_None); - file_reporter = default_file_reporter.get(); - } - file_reporter->SetOutputStream(&output_file); - file_reporter->SetErrorStream(&output_file); - } - - std::vector benchmarks; - if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0; - - if (benchmarks.empty()) { - Err << "Failed to match any benchmarks against regex: " << spec << "\n"; - return 0; - } - - if (FLAGS_benchmark_list_tests) { - for (auto const& benchmark : benchmarks) - Out << benchmark.name.str() << "\n"; - } else { - internal::RunBenchmarks(benchmarks, display_reporter, file_reporter); - } - - return benchmarks.size(); -} - -void RegisterMemoryManager(MemoryManager* manager) { - internal::memory_manager = manager; -} - -namespace internal { - -void PrintUsageAndExit() { - fprintf(stdout, - "benchmark" - " [--benchmark_list_tests={true|false}]\n" - " [--benchmark_filter=]\n" - " [--benchmark_min_time=]\n" - " [--benchmark_repetitions=]\n" - " [--benchmark_report_aggregates_only={true|false}]\n" - " [--benchmark_display_aggregates_only={true|false}]\n" - " [--benchmark_format=]\n" - " [--benchmark_out=]\n" - " [--benchmark_out_format=]\n" - " [--benchmark_color={auto|true|false}]\n" - " [--benchmark_counters_tabular={true|false}]\n" - " [--v=]\n"); - exit(0); -} - -void ParseCommandLineFlags(int* argc, char** argv) { - using namespace benchmark; - BenchmarkReporter::Context::executable_name = - (argc && *argc > 0) ? argv[0] : "unknown"; - for (int i = 1; i < *argc; ++i) { - if (ParseBoolFlag(argv[i], "benchmark_list_tests", - &FLAGS_benchmark_list_tests) || - ParseStringFlag(argv[i], "benchmark_filter", &FLAGS_benchmark_filter) || - ParseDoubleFlag(argv[i], "benchmark_min_time", - &FLAGS_benchmark_min_time) || - ParseInt32Flag(argv[i], "benchmark_repetitions", - &FLAGS_benchmark_repetitions) || - ParseBoolFlag(argv[i], "benchmark_report_aggregates_only", - &FLAGS_benchmark_report_aggregates_only) || - ParseBoolFlag(argv[i], "benchmark_display_aggregates_only", - &FLAGS_benchmark_display_aggregates_only) || - ParseStringFlag(argv[i], "benchmark_format", &FLAGS_benchmark_format) || - ParseStringFlag(argv[i], "benchmark_out", &FLAGS_benchmark_out) || - ParseStringFlag(argv[i], "benchmark_out_format", - &FLAGS_benchmark_out_format) || - ParseStringFlag(argv[i], "benchmark_color", &FLAGS_benchmark_color) || - // "color_print" is the deprecated name for "benchmark_color". - // TODO: Remove this. - ParseStringFlag(argv[i], "color_print", &FLAGS_benchmark_color) || - ParseBoolFlag(argv[i], "benchmark_counters_tabular", - &FLAGS_benchmark_counters_tabular) || - ParseInt32Flag(argv[i], "v", &FLAGS_v)) { - for (int j = i; j != *argc - 1; ++j) argv[j] = argv[j + 1]; - - --(*argc); - --i; - } else if (IsFlag(argv[i], "help")) { - PrintUsageAndExit(); - } - } - for (auto const* flag : - {&FLAGS_benchmark_format, &FLAGS_benchmark_out_format}) - if (*flag != "console" && *flag != "json" && *flag != "csv") { - PrintUsageAndExit(); - } - if (FLAGS_benchmark_color.empty()) { - PrintUsageAndExit(); - } -} - -int InitializeStreams() { - static std::ios_base::Init init; - return 0; -} - -} // end namespace internal - -void Initialize(int* argc, char** argv) { - internal::ParseCommandLineFlags(argc, argv); - internal::LogLevel() = FLAGS_v; -} - -bool ReportUnrecognizedArguments(int argc, char** argv) { - for (int i = 1; i < argc; ++i) { - fprintf(stderr, "%s: error: unrecognized command-line flag: %s\n", argv[0], - argv[i]); - } - return argc > 1; -} - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_api_internal.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_api_internal.cc deleted file mode 100644 index d468a257e39..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_api_internal.cc +++ /dev/null @@ -1,15 +0,0 @@ -#include "benchmark_api_internal.h" - -namespace benchmark { -namespace internal { - -State BenchmarkInstance::Run(IterationCount iters, int thread_id, - internal::ThreadTimer* timer, - internal::ThreadManager* manager) const { - State st(iters, arg, thread_id, threads, timer, manager); - benchmark->Run(st); - return st; -} - -} // internal -} // benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_api_internal.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_api_internal.h deleted file mode 100644 index 264eff95c5c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_api_internal.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef BENCHMARK_API_INTERNAL_H -#define BENCHMARK_API_INTERNAL_H - -#include "benchmark/benchmark.h" -#include "commandlineflags.h" - -#include -#include -#include -#include -#include -#include - -namespace benchmark { -namespace internal { - -// Information kept per benchmark we may want to run -struct BenchmarkInstance { - BenchmarkName name; - Benchmark* benchmark; - AggregationReportMode aggregation_report_mode; - std::vector arg; - TimeUnit time_unit; - int range_multiplier; - bool measure_process_cpu_time; - bool use_real_time; - bool use_manual_time; - BigO complexity; - BigOFunc* complexity_lambda; - UserCounters counters; - const std::vector* statistics; - bool last_benchmark_instance; - int repetitions; - double min_time; - IterationCount iterations; - int threads; // Number of concurrent threads to us - - State Run(IterationCount iters, int thread_id, internal::ThreadTimer* timer, - internal::ThreadManager* manager) const; -}; - -bool FindBenchmarksInternal(const std::string& re, - std::vector* benchmarks, - std::ostream* Err); - -bool IsZero(double n); - -ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color = false); - -} // end namespace internal -} // end namespace benchmark - -#endif // BENCHMARK_API_INTERNAL_H diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_main.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_main.cc deleted file mode 100644 index b3b24783149..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_main.cc +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_name.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_name.cc deleted file mode 100644 index 2a17ebce277..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_name.cc +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include - -namespace benchmark { - -namespace { - -// Compute the total size of a pack of std::strings -size_t size_impl() { return 0; } - -template -size_t size_impl(const Head& head, const Tail&... tail) { - return head.size() + size_impl(tail...); -} - -// Join a pack of std::strings using a delimiter -// TODO: use absl::StrJoin -void join_impl(std::string&, char) {} - -template -void join_impl(std::string& s, const char delimiter, const Head& head, - const Tail&... tail) { - if (!s.empty() && !head.empty()) { - s += delimiter; - } - - s += head; - - join_impl(s, delimiter, tail...); -} - -template -std::string join(char delimiter, const Ts&... ts) { - std::string s; - s.reserve(sizeof...(Ts) + size_impl(ts...)); - join_impl(s, delimiter, ts...); - return s; -} -} // namespace - -std::string BenchmarkName::str() const { - return join('/', function_name, args, min_time, iterations, repetitions, - time_type, threads); -} -} // namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_register.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_register.cc deleted file mode 100644 index 6696c382b80..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_register.cc +++ /dev/null @@ -1,504 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark_register.h" - -#ifndef BENCHMARK_OS_WINDOWS -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define __STDC_FORMAT_MACROS -#include - -#include "benchmark/benchmark.h" -#include "benchmark_api_internal.h" -#include "check.h" -#include "commandlineflags.h" -#include "complexity.h" -#include "internal_macros.h" -#include "log.h" -#include "mutex.h" -#include "re.h" -#include "statistics.h" -#include "string_util.h" -#include "timers.h" - -namespace benchmark { - -namespace { -// For non-dense Range, intermediate values are powers of kRangeMultiplier. -static const int kRangeMultiplier = 8; -// The size of a benchmark family determines is the number of inputs to repeat -// the benchmark on. If this is "large" then warn the user during configuration. -static const size_t kMaxFamilySize = 100; -} // end namespace - -namespace internal { - -//=============================================================================// -// BenchmarkFamilies -//=============================================================================// - -// Class for managing registered benchmarks. Note that each registered -// benchmark identifies a family of related benchmarks to run. -class BenchmarkFamilies { - public: - static BenchmarkFamilies* GetInstance(); - - // Registers a benchmark family and returns the index assigned to it. - size_t AddBenchmark(std::unique_ptr family); - - // Clear all registered benchmark families. - void ClearBenchmarks(); - - // Extract the list of benchmark instances that match the specified - // regular expression. - bool FindBenchmarks(std::string re, - std::vector* benchmarks, - std::ostream* Err); - - private: - BenchmarkFamilies() {} - - std::vector> families_; - Mutex mutex_; -}; - -BenchmarkFamilies* BenchmarkFamilies::GetInstance() { - static BenchmarkFamilies instance; - return &instance; -} - -size_t BenchmarkFamilies::AddBenchmark(std::unique_ptr family) { - MutexLock l(mutex_); - size_t index = families_.size(); - families_.push_back(std::move(family)); - return index; -} - -void BenchmarkFamilies::ClearBenchmarks() { - MutexLock l(mutex_); - families_.clear(); - families_.shrink_to_fit(); -} - -bool BenchmarkFamilies::FindBenchmarks( - std::string spec, std::vector* benchmarks, - std::ostream* ErrStream) { - CHECK(ErrStream); - auto& Err = *ErrStream; - // Make regular expression out of command-line flag - std::string error_msg; - Regex re; - bool isNegativeFilter = false; - if (spec[0] == '-') { - spec.replace(0, 1, ""); - isNegativeFilter = true; - } - if (!re.Init(spec, &error_msg)) { - Err << "Could not compile benchmark re: " << error_msg << std::endl; - return false; - } - - // Special list of thread counts to use when none are specified - const std::vector one_thread = {1}; - - MutexLock l(mutex_); - for (std::unique_ptr& family : families_) { - // Family was deleted or benchmark doesn't match - if (!family) continue; - - if (family->ArgsCnt() == -1) { - family->Args({}); - } - const std::vector* thread_counts = - (family->thread_counts_.empty() - ? &one_thread - : &static_cast&>(family->thread_counts_)); - const size_t family_size = family->args_.size() * thread_counts->size(); - // The benchmark will be run at least 'family_size' different inputs. - // If 'family_size' is very large warn the user. - if (family_size > kMaxFamilySize) { - Err << "The number of inputs is very large. " << family->name_ - << " will be repeated at least " << family_size << " times.\n"; - } - // reserve in the special case the regex ".", since we know the final - // family size. - if (spec == ".") benchmarks->reserve(family_size); - - for (auto const& args : family->args_) { - for (int num_threads : *thread_counts) { - BenchmarkInstance instance; - instance.name.function_name = family->name_; - instance.benchmark = family.get(); - instance.aggregation_report_mode = family->aggregation_report_mode_; - instance.arg = args; - instance.time_unit = family->time_unit_; - instance.range_multiplier = family->range_multiplier_; - instance.min_time = family->min_time_; - instance.iterations = family->iterations_; - instance.repetitions = family->repetitions_; - instance.measure_process_cpu_time = family->measure_process_cpu_time_; - instance.use_real_time = family->use_real_time_; - instance.use_manual_time = family->use_manual_time_; - instance.complexity = family->complexity_; - instance.complexity_lambda = family->complexity_lambda_; - instance.statistics = &family->statistics_; - instance.threads = num_threads; - - // Add arguments to instance name - size_t arg_i = 0; - for (auto const& arg : args) { - if (!instance.name.args.empty()) { - instance.name.args += '/'; - } - - if (arg_i < family->arg_names_.size()) { - const auto& arg_name = family->arg_names_[arg_i]; - if (!arg_name.empty()) { - instance.name.args += StrFormat("%s:", arg_name.c_str()); - } - } - - instance.name.args += StrFormat("%" PRId64, arg); - ++arg_i; - } - - if (!IsZero(family->min_time_)) - instance.name.min_time = - StrFormat("min_time:%0.3f", family->min_time_); - if (family->iterations_ != 0) { - instance.name.iterations = - StrFormat("iterations:%lu", - static_cast(family->iterations_)); - } - if (family->repetitions_ != 0) - instance.name.repetitions = - StrFormat("repeats:%d", family->repetitions_); - - if (family->measure_process_cpu_time_) { - instance.name.time_type = "process_time"; - } - - if (family->use_manual_time_) { - if (!instance.name.time_type.empty()) { - instance.name.time_type += '/'; - } - instance.name.time_type += "manual_time"; - } else if (family->use_real_time_) { - if (!instance.name.time_type.empty()) { - instance.name.time_type += '/'; - } - instance.name.time_type += "real_time"; - } - - // Add the number of threads used to the name - if (!family->thread_counts_.empty()) { - instance.name.threads = StrFormat("threads:%d", instance.threads); - } - - const auto full_name = instance.name.str(); - if ((re.Match(full_name) && !isNegativeFilter) || - (!re.Match(full_name) && isNegativeFilter)) { - instance.last_benchmark_instance = (&args == &family->args_.back()); - benchmarks->push_back(std::move(instance)); - } - } - } - } - return true; -} - -Benchmark* RegisterBenchmarkInternal(Benchmark* bench) { - std::unique_ptr bench_ptr(bench); - BenchmarkFamilies* families = BenchmarkFamilies::GetInstance(); - families->AddBenchmark(std::move(bench_ptr)); - return bench; -} - -// FIXME: This function is a hack so that benchmark.cc can access -// `BenchmarkFamilies` -bool FindBenchmarksInternal(const std::string& re, - std::vector* benchmarks, - std::ostream* Err) { - return BenchmarkFamilies::GetInstance()->FindBenchmarks(re, benchmarks, Err); -} - -//=============================================================================// -// Benchmark -//=============================================================================// - -Benchmark::Benchmark(const char* name) - : name_(name), - aggregation_report_mode_(ARM_Unspecified), - time_unit_(kNanosecond), - range_multiplier_(kRangeMultiplier), - min_time_(0), - iterations_(0), - repetitions_(0), - measure_process_cpu_time_(false), - use_real_time_(false), - use_manual_time_(false), - complexity_(oNone), - complexity_lambda_(nullptr) { - ComputeStatistics("mean", StatisticsMean); - ComputeStatistics("median", StatisticsMedian); - ComputeStatistics("stddev", StatisticsStdDev); -} - -Benchmark::~Benchmark() {} - -Benchmark* Benchmark::Arg(int64_t x) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); - args_.push_back({x}); - return this; -} - -Benchmark* Benchmark::Unit(TimeUnit unit) { - time_unit_ = unit; - return this; -} - -Benchmark* Benchmark::Range(int64_t start, int64_t limit) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); - std::vector arglist; - AddRange(&arglist, start, limit, range_multiplier_); - - for (int64_t i : arglist) { - args_.push_back({i}); - } - return this; -} - -Benchmark* Benchmark::Ranges( - const std::vector>& ranges) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(ranges.size())); - std::vector> arglists(ranges.size()); - std::size_t total = 1; - for (std::size_t i = 0; i < ranges.size(); i++) { - AddRange(&arglists[i], ranges[i].first, ranges[i].second, - range_multiplier_); - total *= arglists[i].size(); - } - - std::vector ctr(arglists.size(), 0); - - for (std::size_t i = 0; i < total; i++) { - std::vector tmp; - tmp.reserve(arglists.size()); - - for (std::size_t j = 0; j < arglists.size(); j++) { - tmp.push_back(arglists[j].at(ctr[j])); - } - - args_.push_back(std::move(tmp)); - - for (std::size_t j = 0; j < arglists.size(); j++) { - if (ctr[j] + 1 < arglists[j].size()) { - ++ctr[j]; - break; - } - ctr[j] = 0; - } - } - return this; -} - -Benchmark* Benchmark::ArgName(const std::string& name) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); - arg_names_ = {name}; - return this; -} - -Benchmark* Benchmark::ArgNames(const std::vector& names) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(names.size())); - arg_names_ = names; - return this; -} - -Benchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == 1); - CHECK_LE(start, limit); - for (int64_t arg = start; arg <= limit; arg += step) { - args_.push_back({arg}); - } - return this; -} - -Benchmark* Benchmark::Args(const std::vector& args) { - CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast(args.size())); - args_.push_back(args); - return this; -} - -Benchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) { - custom_arguments(this); - return this; -} - -Benchmark* Benchmark::RangeMultiplier(int multiplier) { - CHECK(multiplier > 1); - range_multiplier_ = multiplier; - return this; -} - -Benchmark* Benchmark::MinTime(double t) { - CHECK(t > 0.0); - CHECK(iterations_ == 0); - min_time_ = t; - return this; -} - -Benchmark* Benchmark::Iterations(IterationCount n) { - CHECK(n > 0); - CHECK(IsZero(min_time_)); - iterations_ = n; - return this; -} - -Benchmark* Benchmark::Repetitions(int n) { - CHECK(n > 0); - repetitions_ = n; - return this; -} - -Benchmark* Benchmark::ReportAggregatesOnly(bool value) { - aggregation_report_mode_ = value ? ARM_ReportAggregatesOnly : ARM_Default; - return this; -} - -Benchmark* Benchmark::DisplayAggregatesOnly(bool value) { - // If we were called, the report mode is no longer 'unspecified', in any case. - aggregation_report_mode_ = static_cast( - aggregation_report_mode_ | ARM_Default); - - if (value) { - aggregation_report_mode_ = static_cast( - aggregation_report_mode_ | ARM_DisplayReportAggregatesOnly); - } else { - aggregation_report_mode_ = static_cast( - aggregation_report_mode_ & ~ARM_DisplayReportAggregatesOnly); - } - - return this; -} - -Benchmark* Benchmark::MeasureProcessCPUTime() { - // Can be used together with UseRealTime() / UseManualTime(). - measure_process_cpu_time_ = true; - return this; -} - -Benchmark* Benchmark::UseRealTime() { - CHECK(!use_manual_time_) - << "Cannot set UseRealTime and UseManualTime simultaneously."; - use_real_time_ = true; - return this; -} - -Benchmark* Benchmark::UseManualTime() { - CHECK(!use_real_time_) - << "Cannot set UseRealTime and UseManualTime simultaneously."; - use_manual_time_ = true; - return this; -} - -Benchmark* Benchmark::Complexity(BigO complexity) { - complexity_ = complexity; - return this; -} - -Benchmark* Benchmark::Complexity(BigOFunc* complexity) { - complexity_lambda_ = complexity; - complexity_ = oLambda; - return this; -} - -Benchmark* Benchmark::ComputeStatistics(std::string name, - StatisticsFunc* statistics) { - statistics_.emplace_back(name, statistics); - return this; -} - -Benchmark* Benchmark::Threads(int t) { - CHECK_GT(t, 0); - thread_counts_.push_back(t); - return this; -} - -Benchmark* Benchmark::ThreadRange(int min_threads, int max_threads) { - CHECK_GT(min_threads, 0); - CHECK_GE(max_threads, min_threads); - - AddRange(&thread_counts_, min_threads, max_threads, 2); - return this; -} - -Benchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads, - int stride) { - CHECK_GT(min_threads, 0); - CHECK_GE(max_threads, min_threads); - CHECK_GE(stride, 1); - - for (auto i = min_threads; i < max_threads; i += stride) { - thread_counts_.push_back(i); - } - thread_counts_.push_back(max_threads); - return this; -} - -Benchmark* Benchmark::ThreadPerCpu() { - thread_counts_.push_back(CPUInfo::Get().num_cpus); - return this; -} - -void Benchmark::SetName(const char* name) { name_ = name; } - -int Benchmark::ArgsCnt() const { - if (args_.empty()) { - if (arg_names_.empty()) return -1; - return static_cast(arg_names_.size()); - } - return static_cast(args_.front().size()); -} - -//=============================================================================// -// FunctionBenchmark -//=============================================================================// - -void FunctionBenchmark::Run(State& st) { func_(st); } - -} // end namespace internal - -void ClearRegisteredBenchmarks() { - internal::BenchmarkFamilies::GetInstance()->ClearBenchmarks(); -} - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_register.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_register.h deleted file mode 100644 index 61377d74230..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_register.h +++ /dev/null @@ -1,107 +0,0 @@ -#ifndef BENCHMARK_REGISTER_H -#define BENCHMARK_REGISTER_H - -#include - -#include "check.h" - -namespace benchmark { -namespace internal { - -// Append the powers of 'mult' in the closed interval [lo, hi]. -// Returns iterator to the start of the inserted range. -template -typename std::vector::iterator -AddPowers(std::vector* dst, T lo, T hi, int mult) { - CHECK_GE(lo, 0); - CHECK_GE(hi, lo); - CHECK_GE(mult, 2); - - const size_t start_offset = dst->size(); - - static const T kmax = std::numeric_limits::max(); - - // Space out the values in multiples of "mult" - for (T i = 1; i <= hi; i *= mult) { - if (i >= lo) { - dst->push_back(i); - } - // Break the loop here since multiplying by - // 'mult' would move outside of the range of T - if (i > kmax / mult) break; - } - - return dst->begin() + start_offset; -} - -template -void AddNegatedPowers(std::vector* dst, T lo, T hi, int mult) { - // We negate lo and hi so we require that they cannot be equal to 'min'. - CHECK_GT(lo, std::numeric_limits::min()); - CHECK_GT(hi, std::numeric_limits::min()); - CHECK_GE(hi, lo); - CHECK_LE(hi, 0); - - // Add positive powers, then negate and reverse. - // Casts necessary since small integers get promoted - // to 'int' when negating. - const auto lo_complement = static_cast(-lo); - const auto hi_complement = static_cast(-hi); - - const auto it = AddPowers(dst, hi_complement, lo_complement, mult); - - std::for_each(it, dst->end(), [](T& t) { t *= -1; }); - std::reverse(it, dst->end()); -} - -template -void AddRange(std::vector* dst, T lo, T hi, int mult) { - static_assert(std::is_integral::value && std::is_signed::value, - "Args type must be a signed integer"); - - CHECK_GE(hi, lo); - CHECK_GE(mult, 2); - - // Add "lo" - dst->push_back(lo); - - // Handle lo == hi as a special case, so we then know - // lo < hi and so it is safe to add 1 to lo and subtract 1 - // from hi without falling outside of the range of T. - if (lo == hi) return; - - // Ensure that lo_inner <= hi_inner below. - if (lo + 1 == hi) { - dst->push_back(hi); - return; - } - - // Add all powers of 'mult' in the range [lo+1, hi-1] (inclusive). - const auto lo_inner = static_cast(lo + 1); - const auto hi_inner = static_cast(hi - 1); - - // Insert negative values - if (lo_inner < 0) { - AddNegatedPowers(dst, lo_inner, std::min(hi_inner, T{-1}), mult); - } - - // Treat 0 as a special case (see discussion on #762). - if (lo <= 0 && hi >= 0) { - dst->push_back(0); - } - - // Insert positive values - if (hi_inner > 0) { - AddPowers(dst, std::max(lo_inner, T{1}), hi_inner, mult); - } - - // Add "hi" (if different from last value). - if (hi != dst->back()) { - dst->push_back(hi); - } -} - -} // namespace internal -} // namespace benchmark - -#endif // BENCHMARK_REGISTER_H diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_runner.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_runner.cc deleted file mode 100644 index 0bae6a545ef..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_runner.cc +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark_runner.h" -#include "benchmark/benchmark.h" -#include "benchmark_api_internal.h" -#include "internal_macros.h" - -#ifndef BENCHMARK_OS_WINDOWS -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "colorprint.h" -#include "commandlineflags.h" -#include "complexity.h" -#include "counter.h" -#include "internal_macros.h" -#include "log.h" -#include "mutex.h" -#include "re.h" -#include "statistics.h" -#include "string_util.h" -#include "thread_manager.h" -#include "thread_timer.h" - -namespace benchmark { - -namespace internal { - -MemoryManager* memory_manager = nullptr; - -namespace { - -static constexpr IterationCount kMaxIterations = 1000000000; - -BenchmarkReporter::Run CreateRunReport( - const benchmark::internal::BenchmarkInstance& b, - const internal::ThreadManager::Result& results, - IterationCount memory_iterations, - const MemoryManager::Result& memory_result, double seconds, - int64_t repetition_index) { - // Create report about this benchmark run. - BenchmarkReporter::Run report; - - report.run_name = b.name; - report.error_occurred = results.has_error_; - report.error_message = results.error_message_; - report.report_label = results.report_label_; - // This is the total iterations across all threads. - report.iterations = results.iterations; - report.time_unit = b.time_unit; - report.threads = b.threads; - report.repetition_index = repetition_index; - report.repetitions = b.repetitions; - - if (!report.error_occurred) { - if (b.use_manual_time) { - report.real_accumulated_time = results.manual_time_used; - } else { - report.real_accumulated_time = results.real_time_used; - } - report.cpu_accumulated_time = results.cpu_time_used; - report.complexity_n = results.complexity_n; - report.complexity = b.complexity; - report.complexity_lambda = b.complexity_lambda; - report.statistics = b.statistics; - report.counters = results.counters; - - if (memory_iterations > 0) { - report.has_memory_result = true; - report.allocs_per_iter = - memory_iterations ? static_cast(memory_result.num_allocs) / - memory_iterations - : 0; - report.max_bytes_used = memory_result.max_bytes_used; - } - - internal::Finish(&report.counters, results.iterations, seconds, b.threads); - } - return report; -} - -// Execute one thread of benchmark b for the specified number of iterations. -// Adds the stats collected for the thread into *total. -void RunInThread(const BenchmarkInstance* b, IterationCount iters, - int thread_id, ThreadManager* manager) { - internal::ThreadTimer timer( - b->measure_process_cpu_time - ? internal::ThreadTimer::CreateProcessCpuTime() - : internal::ThreadTimer::Create()); - State st = b->Run(iters, thread_id, &timer, manager); - CHECK(st.iterations() >= st.max_iterations) - << "Benchmark returned before State::KeepRunning() returned false!"; - { - MutexLock l(manager->GetBenchmarkMutex()); - internal::ThreadManager::Result& results = manager->results; - results.iterations += st.iterations(); - results.cpu_time_used += timer.cpu_time_used(); - results.real_time_used += timer.real_time_used(); - results.manual_time_used += timer.manual_time_used(); - results.complexity_n += st.complexity_length_n(); - internal::Increment(&results.counters, st.counters); - } - manager->NotifyThreadComplete(); -} - -class BenchmarkRunner { - public: - BenchmarkRunner(const benchmark::internal::BenchmarkInstance& b_, - std::vector* complexity_reports_) - : b(b_), - complexity_reports(*complexity_reports_), - min_time(!IsZero(b.min_time) ? b.min_time : FLAGS_benchmark_min_time), - repeats(b.repetitions != 0 ? b.repetitions - : FLAGS_benchmark_repetitions), - has_explicit_iteration_count(b.iterations != 0), - pool(b.threads - 1), - iters(has_explicit_iteration_count ? b.iterations : 1) { - run_results.display_report_aggregates_only = - (FLAGS_benchmark_report_aggregates_only || - FLAGS_benchmark_display_aggregates_only); - run_results.file_report_aggregates_only = - FLAGS_benchmark_report_aggregates_only; - if (b.aggregation_report_mode != internal::ARM_Unspecified) { - run_results.display_report_aggregates_only = - (b.aggregation_report_mode & - internal::ARM_DisplayReportAggregatesOnly); - run_results.file_report_aggregates_only = - (b.aggregation_report_mode & internal::ARM_FileReportAggregatesOnly); - } - - for (int repetition_num = 0; repetition_num < repeats; repetition_num++) { - DoOneRepetition(repetition_num); - } - - // Calculate additional statistics - run_results.aggregates_only = ComputeStats(run_results.non_aggregates); - - // Maybe calculate complexity report - if ((b.complexity != oNone) && b.last_benchmark_instance) { - auto additional_run_stats = ComputeBigO(complexity_reports); - run_results.aggregates_only.insert(run_results.aggregates_only.end(), - additional_run_stats.begin(), - additional_run_stats.end()); - complexity_reports.clear(); - } - } - - RunResults&& get_results() { return std::move(run_results); } - - private: - RunResults run_results; - - const benchmark::internal::BenchmarkInstance& b; - std::vector& complexity_reports; - - const double min_time; - const int repeats; - const bool has_explicit_iteration_count; - - std::vector pool; - - IterationCount iters; // preserved between repetitions! - // So only the first repetition has to find/calculate it, - // the other repetitions will just use that precomputed iteration count. - - struct IterationResults { - internal::ThreadManager::Result results; - IterationCount iters; - double seconds; - }; - IterationResults DoNIterations() { - VLOG(2) << "Running " << b.name.str() << " for " << iters << "\n"; - - std::unique_ptr manager; - manager.reset(new internal::ThreadManager(b.threads)); - - // Run all but one thread in separate threads - for (std::size_t ti = 0; ti < pool.size(); ++ti) { - pool[ti] = std::thread(&RunInThread, &b, iters, static_cast(ti + 1), - manager.get()); - } - // And run one thread here directly. - // (If we were asked to run just one thread, we don't create new threads.) - // Yes, we need to do this here *after* we start the separate threads. - RunInThread(&b, iters, 0, manager.get()); - - // The main thread has finished. Now let's wait for the other threads. - manager->WaitForAllThreads(); - for (std::thread& thread : pool) thread.join(); - - IterationResults i; - // Acquire the measurements/counters from the manager, UNDER THE LOCK! - { - MutexLock l(manager->GetBenchmarkMutex()); - i.results = manager->results; - } - - // And get rid of the manager. - manager.reset(); - - // Adjust real/manual time stats since they were reported per thread. - i.results.real_time_used /= b.threads; - i.results.manual_time_used /= b.threads; - // If we were measuring whole-process CPU usage, adjust the CPU time too. - if (b.measure_process_cpu_time) i.results.cpu_time_used /= b.threads; - - VLOG(2) << "Ran in " << i.results.cpu_time_used << "/" - << i.results.real_time_used << "\n"; - - // So for how long were we running? - i.iters = iters; - // Base decisions off of real time if requested by this benchmark. - i.seconds = i.results.cpu_time_used; - if (b.use_manual_time) { - i.seconds = i.results.manual_time_used; - } else if (b.use_real_time) { - i.seconds = i.results.real_time_used; - } - - return i; - } - - IterationCount PredictNumItersNeeded(const IterationResults& i) const { - // See how much iterations should be increased by. - // Note: Avoid division by zero with max(seconds, 1ns). - double multiplier = min_time * 1.4 / std::max(i.seconds, 1e-9); - // If our last run was at least 10% of FLAGS_benchmark_min_time then we - // use the multiplier directly. - // Otherwise we use at most 10 times expansion. - // NOTE: When the last run was at least 10% of the min time the max - // expansion should be 14x. - bool is_significant = (i.seconds / min_time) > 0.1; - multiplier = is_significant ? multiplier : std::min(10.0, multiplier); - if (multiplier <= 1.0) multiplier = 2.0; - - // So what seems to be the sufficiently-large iteration count? Round up. - const IterationCount max_next_iters = - 0.5 + std::max(multiplier * i.iters, i.iters + 1.0); - // But we do have *some* sanity limits though.. - const IterationCount next_iters = std::min(max_next_iters, kMaxIterations); - - VLOG(3) << "Next iters: " << next_iters << ", " << multiplier << "\n"; - return next_iters; // round up before conversion to integer. - } - - bool ShouldReportIterationResults(const IterationResults& i) const { - // Determine if this run should be reported; - // Either it has run for a sufficient amount of time - // or because an error was reported. - return i.results.has_error_ || - i.iters >= kMaxIterations || // Too many iterations already. - i.seconds >= min_time || // The elapsed time is large enough. - // CPU time is specified but the elapsed real time greatly exceeds - // the minimum time. - // Note that user provided timers are except from this sanity check. - ((i.results.real_time_used >= 5 * min_time) && !b.use_manual_time); - } - - void DoOneRepetition(int64_t repetition_index) { - const bool is_the_first_repetition = repetition_index == 0; - IterationResults i; - - // We *may* be gradually increasing the length (iteration count) - // of the benchmark until we decide the results are significant. - // And once we do, we report those last results and exit. - // Please do note that the if there are repetitions, the iteration count - // is *only* calculated for the *first* repetition, and other repetitions - // simply use that precomputed iteration count. - for (;;) { - i = DoNIterations(); - - // Do we consider the results to be significant? - // If we are doing repetitions, and the first repetition was already done, - // it has calculated the correct iteration time, so we have run that very - // iteration count just now. No need to calculate anything. Just report. - // Else, the normal rules apply. - const bool results_are_significant = !is_the_first_repetition || - has_explicit_iteration_count || - ShouldReportIterationResults(i); - - if (results_are_significant) break; // Good, let's report them! - - // Nope, bad iteration. Let's re-estimate the hopefully-sufficient - // iteration count, and run the benchmark again... - - iters = PredictNumItersNeeded(i); - assert(iters > i.iters && - "if we did more iterations than we want to do the next time, " - "then we should have accepted the current iteration run."); - } - - // Oh, one last thing, we need to also produce the 'memory measurements'.. - MemoryManager::Result memory_result; - IterationCount memory_iterations = 0; - if (memory_manager != nullptr) { - // Only run a few iterations to reduce the impact of one-time - // allocations in benchmarks that are not properly managed. - memory_iterations = std::min(16, iters); - memory_manager->Start(); - std::unique_ptr manager; - manager.reset(new internal::ThreadManager(1)); - RunInThread(&b, memory_iterations, 0, manager.get()); - manager->WaitForAllThreads(); - manager.reset(); - - memory_manager->Stop(&memory_result); - } - - // Ok, now actualy report. - BenchmarkReporter::Run report = - CreateRunReport(b, i.results, memory_iterations, memory_result, - i.seconds, repetition_index); - - if (!report.error_occurred && b.complexity != oNone) - complexity_reports.push_back(report); - - run_results.non_aggregates.push_back(report); - } -}; - -} // end namespace - -RunResults RunBenchmark( - const benchmark::internal::BenchmarkInstance& b, - std::vector* complexity_reports) { - internal::BenchmarkRunner r(b, complexity_reports); - return r.get_results(); -} - -} // end namespace internal - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_runner.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_runner.h deleted file mode 100644 index 96e8282a11a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/benchmark_runner.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef BENCHMARK_RUNNER_H_ -#define BENCHMARK_RUNNER_H_ - -#include "benchmark_api_internal.h" -#include "internal_macros.h" - -DECLARE_double(benchmark_min_time); - -DECLARE_int32(benchmark_repetitions); - -DECLARE_bool(benchmark_report_aggregates_only); - -DECLARE_bool(benchmark_display_aggregates_only); - -namespace benchmark { - -namespace internal { - -extern MemoryManager* memory_manager; - -struct RunResults { - std::vector non_aggregates; - std::vector aggregates_only; - - bool display_report_aggregates_only = false; - bool file_report_aggregates_only = false; -}; - -RunResults RunBenchmark( - const benchmark::internal::BenchmarkInstance& b, - std::vector* complexity_reports); - -} // namespace internal - -} // end namespace benchmark - -#endif // BENCHMARK_RUNNER_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/check.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/check.h deleted file mode 100644 index f5f8253f804..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/check.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef CHECK_H_ -#define CHECK_H_ - -#include -#include -#include - -#include "internal_macros.h" -#include "log.h" - -namespace benchmark { -namespace internal { - -typedef void(AbortHandlerT)(); - -inline AbortHandlerT*& GetAbortHandler() { - static AbortHandlerT* handler = &std::abort; - return handler; -} - -BENCHMARK_NORETURN inline void CallAbortHandler() { - GetAbortHandler()(); - std::abort(); // fallback to enforce noreturn -} - -// CheckHandler is the class constructed by failing CHECK macros. CheckHandler -// will log information about the failures and abort when it is destructed. -class CheckHandler { - public: - CheckHandler(const char* check, const char* file, const char* func, int line) - : log_(GetErrorLogInstance()) { - log_ << file << ":" << line << ": " << func << ": Check `" << check - << "' failed. "; - } - - LogType& GetLog() { return log_; } - - BENCHMARK_NORETURN ~CheckHandler() BENCHMARK_NOEXCEPT_OP(false) { - log_ << std::endl; - CallAbortHandler(); - } - - CheckHandler& operator=(const CheckHandler&) = delete; - CheckHandler(const CheckHandler&) = delete; - CheckHandler() = delete; - - private: - LogType& log_; -}; - -} // end namespace internal -} // end namespace benchmark - -// The CHECK macro returns a std::ostream object that can have extra information -// written to it. -#ifndef NDEBUG -#define CHECK(b) \ - (b ? ::benchmark::internal::GetNullLogInstance() \ - : ::benchmark::internal::CheckHandler(#b, __FILE__, __func__, __LINE__) \ - .GetLog()) -#else -#define CHECK(b) ::benchmark::internal::GetNullLogInstance() -#endif - -// clang-format off -// preserve whitespacing between operators for alignment -#define CHECK_EQ(a, b) CHECK((a) == (b)) -#define CHECK_NE(a, b) CHECK((a) != (b)) -#define CHECK_GE(a, b) CHECK((a) >= (b)) -#define CHECK_LE(a, b) CHECK((a) <= (b)) -#define CHECK_GT(a, b) CHECK((a) > (b)) -#define CHECK_LT(a, b) CHECK((a) < (b)) - -#define CHECK_FLOAT_EQ(a, b, eps) CHECK(std::fabs((a) - (b)) < (eps)) -#define CHECK_FLOAT_NE(a, b, eps) CHECK(std::fabs((a) - (b)) >= (eps)) -#define CHECK_FLOAT_GE(a, b, eps) CHECK((a) - (b) > -(eps)) -#define CHECK_FLOAT_LE(a, b, eps) CHECK((b) - (a) > -(eps)) -#define CHECK_FLOAT_GT(a, b, eps) CHECK((a) - (b) > (eps)) -#define CHECK_FLOAT_LT(a, b, eps) CHECK((b) - (a) > (eps)) -//clang-format on - -#endif // CHECK_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/colorprint.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/colorprint.cc deleted file mode 100644 index fff6a98818b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/colorprint.cc +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "colorprint.h" - -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "internal_macros.h" - -#ifdef BENCHMARK_OS_WINDOWS -#include -#include -#else -#include -#endif // BENCHMARK_OS_WINDOWS - -namespace benchmark { -namespace { -#ifdef BENCHMARK_OS_WINDOWS -typedef WORD PlatformColorCode; -#else -typedef const char* PlatformColorCode; -#endif - -PlatformColorCode GetPlatformColorCode(LogColor color) { -#ifdef BENCHMARK_OS_WINDOWS - switch (color) { - case COLOR_RED: - return FOREGROUND_RED; - case COLOR_GREEN: - return FOREGROUND_GREEN; - case COLOR_YELLOW: - return FOREGROUND_RED | FOREGROUND_GREEN; - case COLOR_BLUE: - return FOREGROUND_BLUE; - case COLOR_MAGENTA: - return FOREGROUND_BLUE | FOREGROUND_RED; - case COLOR_CYAN: - return FOREGROUND_BLUE | FOREGROUND_GREEN; - case COLOR_WHITE: // fall through to default - default: - return 0; - } -#else - switch (color) { - case COLOR_RED: - return "1"; - case COLOR_GREEN: - return "2"; - case COLOR_YELLOW: - return "3"; - case COLOR_BLUE: - return "4"; - case COLOR_MAGENTA: - return "5"; - case COLOR_CYAN: - return "6"; - case COLOR_WHITE: - return "7"; - default: - return nullptr; - }; -#endif -} - -} // end namespace - -std::string FormatString(const char* msg, va_list args) { - // we might need a second shot at this, so pre-emptivly make a copy - va_list args_cp; - va_copy(args_cp, args); - - std::size_t size = 256; - char local_buff[256]; - auto ret = vsnprintf(local_buff, size, msg, args_cp); - - va_end(args_cp); - - // currently there is no error handling for failure, so this is hack. - CHECK(ret >= 0); - - if (ret == 0) // handle empty expansion - return {}; - else if (static_cast(ret) < size) - return local_buff; - else { - // we did not provide a long enough buffer on our first attempt. - size = (size_t)ret + 1; // + 1 for the null byte - std::unique_ptr buff(new char[size]); - ret = vsnprintf(buff.get(), size, msg, args); - CHECK(ret > 0 && ((size_t)ret) < size); - return buff.get(); - } -} - -std::string FormatString(const char* msg, ...) { - va_list args; - va_start(args, msg); - auto tmp = FormatString(msg, args); - va_end(args); - return tmp; -} - -void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, ...) { - va_list args; - va_start(args, fmt); - ColorPrintf(out, color, fmt, args); - va_end(args); -} - -void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, - va_list args) { -#ifdef BENCHMARK_OS_WINDOWS - ((void)out); // suppress unused warning - - const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); - - // Gets the current text color. - CONSOLE_SCREEN_BUFFER_INFO buffer_info; - GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); - const WORD old_color_attrs = buffer_info.wAttributes; - - // We need to flush the stream buffers into the console before each - // SetConsoleTextAttribute call lest it affect the text that is already - // printed but has not yet reached the console. - fflush(stdout); - SetConsoleTextAttribute(stdout_handle, - GetPlatformColorCode(color) | FOREGROUND_INTENSITY); - vprintf(fmt, args); - - fflush(stdout); - // Restores the text color. - SetConsoleTextAttribute(stdout_handle, old_color_attrs); -#else - const char* color_code = GetPlatformColorCode(color); - if (color_code) out << FormatString("\033[0;3%sm", color_code); - out << FormatString(fmt, args) << "\033[m"; -#endif -} - -bool IsColorTerminal() { -#if BENCHMARK_OS_WINDOWS - // On Windows the TERM variable is usually not set, but the - // console there does support colors. - return 0 != _isatty(_fileno(stdout)); -#else - // On non-Windows platforms, we rely on the TERM variable. This list of - // supported TERM values is copied from Google Test: - // . - const char* const SUPPORTED_TERM_VALUES[] = { - "xterm", "xterm-color", "xterm-256color", - "screen", "screen-256color", "tmux", - "tmux-256color", "rxvt-unicode", "rxvt-unicode-256color", - "linux", "cygwin", - }; - - const char* const term = getenv("TERM"); - - bool term_supports_color = false; - for (const char* candidate : SUPPORTED_TERM_VALUES) { - if (term && 0 == strcmp(term, candidate)) { - term_supports_color = true; - break; - } - } - - return 0 != isatty(fileno(stdout)) && term_supports_color; -#endif // BENCHMARK_OS_WINDOWS -} - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/colorprint.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/colorprint.h deleted file mode 100644 index 9f6fab9b342..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/colorprint.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef BENCHMARK_COLORPRINT_H_ -#define BENCHMARK_COLORPRINT_H_ - -#include -#include -#include - -namespace benchmark { -enum LogColor { - COLOR_DEFAULT, - COLOR_RED, - COLOR_GREEN, - COLOR_YELLOW, - COLOR_BLUE, - COLOR_MAGENTA, - COLOR_CYAN, - COLOR_WHITE -}; - -std::string FormatString(const char* msg, va_list args); -std::string FormatString(const char* msg, ...); - -void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, - va_list args); -void ColorPrintf(std::ostream& out, LogColor color, const char* fmt, ...); - -// Returns true if stdout appears to be a terminal that supports colored -// output, false otherwise. -bool IsColorTerminal(); - -} // end namespace benchmark - -#endif // BENCHMARK_COLORPRINT_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/commandlineflags.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/commandlineflags.cc deleted file mode 100644 index 6bd65c5ae70..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/commandlineflags.cc +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "commandlineflags.h" - -#include -#include -#include -#include -#include - -namespace benchmark { -namespace { - -// Parses 'str' for a 32-bit signed integer. If successful, writes -// the result to *value and returns true; otherwise leaves *value -// unchanged and returns false. -bool ParseInt32(const std::string& src_text, const char* str, int32_t* value) { - // Parses the environment variable as a decimal integer. - char* end = nullptr; - const long long_value = strtol(str, &end, 10); // NOLINT - - // Has strtol() consumed all characters in the string? - if (*end != '\0') { - // No - an invalid character was encountered. - std::cerr << src_text << " is expected to be a 32-bit integer, " - << "but actually has value \"" << str << "\".\n"; - return false; - } - - // Is the parsed value in the range of an Int32? - const int32_t result = static_cast(long_value); - if (long_value == std::numeric_limits::max() || - long_value == std::numeric_limits::min() || - // The parsed value overflows as a long. (strtol() returns - // LONG_MAX or LONG_MIN when the input overflows.) - result != long_value - // The parsed value overflows as an Int32. - ) { - std::cerr << src_text << " is expected to be a 32-bit integer, " - << "but actually has value \"" << str << "\", " - << "which overflows.\n"; - return false; - } - - *value = result; - return true; -} - -// Parses 'str' for a double. If successful, writes the result to *value and -// returns true; otherwise leaves *value unchanged and returns false. -bool ParseDouble(const std::string& src_text, const char* str, double* value) { - // Parses the environment variable as a decimal integer. - char* end = nullptr; - const double double_value = strtod(str, &end); // NOLINT - - // Has strtol() consumed all characters in the string? - if (*end != '\0') { - // No - an invalid character was encountered. - std::cerr << src_text << " is expected to be a double, " - << "but actually has value \"" << str << "\".\n"; - return false; - } - - *value = double_value; - return true; -} - -// Returns the name of the environment variable corresponding to the -// given flag. For example, FlagToEnvVar("foo") will return -// "BENCHMARK_FOO" in the open-source version. -static std::string FlagToEnvVar(const char* flag) { - const std::string flag_str(flag); - - std::string env_var; - for (size_t i = 0; i != flag_str.length(); ++i) - env_var += static_cast(::toupper(flag_str.c_str()[i])); - - return "BENCHMARK_" + env_var; -} - -} // namespace - -// Reads and returns the Boolean environment variable corresponding to -// the given flag; if it's not set, returns default_value. -// -// The value is considered true iff it's not "0". -bool BoolFromEnv(const char* flag, bool default_value) { - const std::string env_var = FlagToEnvVar(flag); - const char* const string_value = getenv(env_var.c_str()); - return string_value == nullptr ? default_value - : strcmp(string_value, "0") != 0; -} - -// Reads and returns a 32-bit integer stored in the environment -// variable corresponding to the given flag; if it isn't set or -// doesn't represent a valid 32-bit integer, returns default_value. -int32_t Int32FromEnv(const char* flag, int32_t default_value) { - const std::string env_var = FlagToEnvVar(flag); - const char* const string_value = getenv(env_var.c_str()); - if (string_value == nullptr) { - // The environment variable is not set. - return default_value; - } - - int32_t result = default_value; - if (!ParseInt32(std::string("Environment variable ") + env_var, string_value, - &result)) { - std::cout << "The default value " << default_value << " is used.\n"; - return default_value; - } - - return result; -} - -// Reads and returns the string environment variable corresponding to -// the given flag; if it's not set, returns default_value. -const char* StringFromEnv(const char* flag, const char* default_value) { - const std::string env_var = FlagToEnvVar(flag); - const char* const value = getenv(env_var.c_str()); - return value == nullptr ? default_value : value; -} - -// Parses a string as a command line flag. The string should have -// the format "--flag=value". When def_optional is true, the "=value" -// part can be omitted. -// -// Returns the value of the flag, or nullptr if the parsing failed. -const char* ParseFlagValue(const char* str, const char* flag, - bool def_optional) { - // str and flag must not be nullptr. - if (str == nullptr || flag == nullptr) return nullptr; - - // The flag must start with "--". - const std::string flag_str = std::string("--") + std::string(flag); - const size_t flag_len = flag_str.length(); - if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; - - // Skips the flag name. - const char* flag_end = str + flag_len; - - // When def_optional is true, it's OK to not have a "=value" part. - if (def_optional && (flag_end[0] == '\0')) return flag_end; - - // If def_optional is true and there are more characters after the - // flag name, or if def_optional is false, there must be a '=' after - // the flag name. - if (flag_end[0] != '=') return nullptr; - - // Returns the string after "=". - return flag_end + 1; -} - -bool ParseBoolFlag(const char* str, const char* flag, bool* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, true); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - // Converts the string value to a bool. - *value = IsTruthyFlagValue(value_str); - return true; -} - -bool ParseInt32Flag(const char* str, const char* flag, int32_t* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - // Sets *value to the value of the flag. - return ParseInt32(std::string("The value of flag --") + flag, value_str, - value); -} - -bool ParseDoubleFlag(const char* str, const char* flag, double* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - // Sets *value to the value of the flag. - return ParseDouble(std::string("The value of flag --") + flag, value_str, - value); -} - -bool ParseStringFlag(const char* str, const char* flag, std::string* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - *value = value_str; - return true; -} - -bool IsFlag(const char* str, const char* flag) { - return (ParseFlagValue(str, flag, true) != nullptr); -} - -bool IsTruthyFlagValue(const std::string& value) { - if (value.empty()) return true; - char ch = value[0]; - return isalnum(ch) && - !(ch == '0' || ch == 'f' || ch == 'F' || ch == 'n' || ch == 'N'); -} -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/commandlineflags.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/commandlineflags.h deleted file mode 100644 index 5eaea82a59b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/commandlineflags.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef BENCHMARK_COMMANDLINEFLAGS_H_ -#define BENCHMARK_COMMANDLINEFLAGS_H_ - -#include -#include - -// Macro for referencing flags. -#define FLAG(name) FLAGS_##name - -// Macros for declaring flags. -#define DECLARE_bool(name) extern bool FLAG(name) -#define DECLARE_int32(name) extern int32_t FLAG(name) -#define DECLARE_int64(name) extern int64_t FLAG(name) -#define DECLARE_double(name) extern double FLAG(name) -#define DECLARE_string(name) extern std::string FLAG(name) - -// Macros for defining flags. -#define DEFINE_bool(name, default_val, doc) bool FLAG(name) = (default_val) -#define DEFINE_int32(name, default_val, doc) int32_t FLAG(name) = (default_val) -#define DEFINE_int64(name, default_val, doc) int64_t FLAG(name) = (default_val) -#define DEFINE_double(name, default_val, doc) double FLAG(name) = (default_val) -#define DEFINE_string(name, default_val, doc) \ - std::string FLAG(name) = (default_val) - -namespace benchmark { -// Parses a bool/Int32/string from the environment variable -// corresponding to the given Google Test flag. -bool BoolFromEnv(const char* flag, bool default_val); -int32_t Int32FromEnv(const char* flag, int32_t default_val); -const char* StringFromEnv(const char* flag, const char* default_val); - -// Parses a string for a bool flag, in the form of either -// "--flag=value" or "--flag". -// -// In the former case, the value is taken as true if it passes IsTruthyValue(). -// -// In the latter case, the value is taken as true. -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseBoolFlag(const char* str, const char* flag, bool* value); - -// Parses a string for an Int32 flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseInt32Flag(const char* str, const char* flag, int32_t* value); - -// Parses a string for a Double flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseDoubleFlag(const char* str, const char* flag, double* value); - -// Parses a string for a string flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseStringFlag(const char* str, const char* flag, std::string* value); - -// Returns true if the string matches the flag. -bool IsFlag(const char* str, const char* flag); - -// Returns true unless value starts with one of: '0', 'f', 'F', 'n' or 'N', or -// some non-alphanumeric character. As a special case, also returns true if -// value is the empty string. -bool IsTruthyFlagValue(const std::string& value); -} // end namespace benchmark - -#endif // BENCHMARK_COMMANDLINEFLAGS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/complexity.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/complexity.cc deleted file mode 100644 index aeed67f0c70..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/complexity.cc +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Source project : https://github.com/ismaelJimenez/cpp.leastsq -// Adapted to be used with google benchmark - -#include "benchmark/benchmark.h" - -#include -#include -#include "check.h" -#include "complexity.h" - -namespace benchmark { - -// Internal function to calculate the different scalability forms -BigOFunc* FittingCurve(BigO complexity) { - static const double kLog2E = 1.44269504088896340736; - switch (complexity) { - case oN: - return [](IterationCount n) -> double { return static_cast(n); }; - case oNSquared: - return [](IterationCount n) -> double { return std::pow(n, 2); }; - case oNCubed: - return [](IterationCount n) -> double { return std::pow(n, 3); }; - case oLogN: - /* Note: can't use log2 because Android's GNU STL lacks it */ - return - [](IterationCount n) { return kLog2E * log(static_cast(n)); }; - case oNLogN: - /* Note: can't use log2 because Android's GNU STL lacks it */ - return [](IterationCount n) { - return kLog2E * n * log(static_cast(n)); - }; - case o1: - default: - return [](IterationCount) { return 1.0; }; - } -} - -// Function to return an string for the calculated complexity -std::string GetBigOString(BigO complexity) { - switch (complexity) { - case oN: - return "N"; - case oNSquared: - return "N^2"; - case oNCubed: - return "N^3"; - case oLogN: - return "lgN"; - case oNLogN: - return "NlgN"; - case o1: - return "(1)"; - default: - return "f(N)"; - } -} - -// Find the coefficient for the high-order term in the running time, by -// minimizing the sum of squares of relative error, for the fitting curve -// given by the lambda expression. -// - n : Vector containing the size of the benchmark tests. -// - time : Vector containing the times for the benchmark tests. -// - fitting_curve : lambda expression (e.g. [](int64_t n) {return n; };). - -// For a deeper explanation on the algorithm logic, please refer to -// https://en.wikipedia.org/wiki/Least_squares#Least_squares,_regression_analysis_and_statistics - -LeastSq MinimalLeastSq(const std::vector& n, - const std::vector& time, - BigOFunc* fitting_curve) { - double sigma_gn = 0.0; - double sigma_gn_squared = 0.0; - double sigma_time = 0.0; - double sigma_time_gn = 0.0; - - // Calculate least square fitting parameter - for (size_t i = 0; i < n.size(); ++i) { - double gn_i = fitting_curve(n[i]); - sigma_gn += gn_i; - sigma_gn_squared += gn_i * gn_i; - sigma_time += time[i]; - sigma_time_gn += time[i] * gn_i; - } - - LeastSq result; - result.complexity = oLambda; - - // Calculate complexity. - result.coef = sigma_time_gn / sigma_gn_squared; - - // Calculate RMS - double rms = 0.0; - for (size_t i = 0; i < n.size(); ++i) { - double fit = result.coef * fitting_curve(n[i]); - rms += pow((time[i] - fit), 2); - } - - // Normalized RMS by the mean of the observed values - double mean = sigma_time / n.size(); - result.rms = sqrt(rms / n.size()) / mean; - - return result; -} - -// Find the coefficient for the high-order term in the running time, by -// minimizing the sum of squares of relative error. -// - n : Vector containing the size of the benchmark tests. -// - time : Vector containing the times for the benchmark tests. -// - complexity : If different than oAuto, the fitting curve will stick to -// this one. If it is oAuto, it will be calculated the best -// fitting curve. -LeastSq MinimalLeastSq(const std::vector& n, - const std::vector& time, const BigO complexity) { - CHECK_EQ(n.size(), time.size()); - CHECK_GE(n.size(), 2); // Do not compute fitting curve is less than two - // benchmark runs are given - CHECK_NE(complexity, oNone); - - LeastSq best_fit; - - if (complexity == oAuto) { - std::vector fit_curves = {oLogN, oN, oNLogN, oNSquared, oNCubed}; - - // Take o1 as default best fitting curve - best_fit = MinimalLeastSq(n, time, FittingCurve(o1)); - best_fit.complexity = o1; - - // Compute all possible fitting curves and stick to the best one - for (const auto& fit : fit_curves) { - LeastSq current_fit = MinimalLeastSq(n, time, FittingCurve(fit)); - if (current_fit.rms < best_fit.rms) { - best_fit = current_fit; - best_fit.complexity = fit; - } - } - } else { - best_fit = MinimalLeastSq(n, time, FittingCurve(complexity)); - best_fit.complexity = complexity; - } - - return best_fit; -} - -std::vector ComputeBigO( - const std::vector& reports) { - typedef BenchmarkReporter::Run Run; - std::vector results; - - if (reports.size() < 2) return results; - - // Accumulators. - std::vector n; - std::vector real_time; - std::vector cpu_time; - - // Populate the accumulators. - for (const Run& run : reports) { - CHECK_GT(run.complexity_n, 0) << "Did you forget to call SetComplexityN?"; - n.push_back(run.complexity_n); - real_time.push_back(run.real_accumulated_time / run.iterations); - cpu_time.push_back(run.cpu_accumulated_time / run.iterations); - } - - LeastSq result_cpu; - LeastSq result_real; - - if (reports[0].complexity == oLambda) { - result_cpu = MinimalLeastSq(n, cpu_time, reports[0].complexity_lambda); - result_real = MinimalLeastSq(n, real_time, reports[0].complexity_lambda); - } else { - result_cpu = MinimalLeastSq(n, cpu_time, reports[0].complexity); - result_real = MinimalLeastSq(n, real_time, result_cpu.complexity); - } - - // Drop the 'args' when reporting complexity. - auto run_name = reports[0].run_name; - run_name.args.clear(); - - // Get the data from the accumulator to BenchmarkReporter::Run's. - Run big_o; - big_o.run_name = run_name; - big_o.run_type = BenchmarkReporter::Run::RT_Aggregate; - big_o.repetitions = reports[0].repetitions; - big_o.repetition_index = Run::no_repetition_index; - big_o.threads = reports[0].threads; - big_o.aggregate_name = "BigO"; - big_o.report_label = reports[0].report_label; - big_o.iterations = 0; - big_o.real_accumulated_time = result_real.coef; - big_o.cpu_accumulated_time = result_cpu.coef; - big_o.report_big_o = true; - big_o.complexity = result_cpu.complexity; - - // All the time results are reported after being multiplied by the - // time unit multiplier. But since RMS is a relative quantity it - // should not be multiplied at all. So, here, we _divide_ it by the - // multiplier so that when it is multiplied later the result is the - // correct one. - double multiplier = GetTimeUnitMultiplier(reports[0].time_unit); - - // Only add label to mean/stddev if it is same for all runs - Run rms; - rms.run_name = run_name; - rms.run_type = BenchmarkReporter::Run::RT_Aggregate; - rms.aggregate_name = "RMS"; - rms.report_label = big_o.report_label; - rms.iterations = 0; - rms.repetition_index = Run::no_repetition_index; - rms.repetitions = reports[0].repetitions; - rms.threads = reports[0].threads; - rms.real_accumulated_time = result_real.rms / multiplier; - rms.cpu_accumulated_time = result_cpu.rms / multiplier; - rms.report_rms = true; - rms.complexity = result_cpu.complexity; - // don't forget to keep the time unit, or we won't be able to - // recover the correct value. - rms.time_unit = reports[0].time_unit; - - results.push_back(big_o); - results.push_back(rms); - return results; -} - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/complexity.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/complexity.h deleted file mode 100644 index df29b48d29b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/complexity.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Source project : https://github.com/ismaelJimenez/cpp.leastsq -// Adapted to be used with google benchmark - -#ifndef COMPLEXITY_H_ -#define COMPLEXITY_H_ - -#include -#include - -#include "benchmark/benchmark.h" - -namespace benchmark { - -// Return a vector containing the bigO and RMS information for the specified -// list of reports. If 'reports.size() < 2' an empty vector is returned. -std::vector ComputeBigO( - const std::vector& reports); - -// This data structure will contain the result returned by MinimalLeastSq -// - coef : Estimated coeficient for the high-order term as -// interpolated from data. -// - rms : Normalized Root Mean Squared Error. -// - complexity : Scalability form (e.g. oN, oNLogN). In case a scalability -// form has been provided to MinimalLeastSq this will return -// the same value. In case BigO::oAuto has been selected, this -// parameter will return the best fitting curve detected. - -struct LeastSq { - LeastSq() : coef(0.0), rms(0.0), complexity(oNone) {} - - double coef; - double rms; - BigO complexity; -}; - -// Function to return an string for the calculated complexity -std::string GetBigOString(BigO complexity); - -} // end namespace benchmark - -#endif // COMPLEXITY_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/console_reporter.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/console_reporter.cc deleted file mode 100644 index cc8ae276f6b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/console_reporter.cc +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "complexity.h" -#include "counter.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "colorprint.h" -#include "commandlineflags.h" -#include "internal_macros.h" -#include "string_util.h" -#include "timers.h" - -namespace benchmark { - -bool ConsoleReporter::ReportContext(const Context& context) { - name_field_width_ = context.name_field_width; - printed_header_ = false; - prev_counters_.clear(); - - PrintBasicContext(&GetErrorStream(), context); - -#ifdef BENCHMARK_OS_WINDOWS - if ((output_options_ & OO_Color) && &std::cout != &GetOutputStream()) { - GetErrorStream() - << "Color printing is only supported for stdout on windows." - " Disabling color printing\n"; - output_options_ = static_cast< OutputOptions >(output_options_ & ~OO_Color); - } -#endif - - return true; -} - -void ConsoleReporter::PrintHeader(const Run& run) { - std::string str = FormatString("%-*s %13s %15s %12s", static_cast(name_field_width_), - "Benchmark", "Time", "CPU", "Iterations"); - if(!run.counters.empty()) { - if(output_options_ & OO_Tabular) { - for(auto const& c : run.counters) { - str += FormatString(" %10s", c.first.c_str()); - } - } else { - str += " UserCounters..."; - } - } - std::string line = std::string(str.length(), '-'); - GetOutputStream() << line << "\n" << str << "\n" << line << "\n"; -} - -void ConsoleReporter::ReportRuns(const std::vector& reports) { - for (const auto& run : reports) { - // print the header: - // --- if none was printed yet - bool print_header = !printed_header_; - // --- or if the format is tabular and this run - // has different fields from the prev header - print_header |= (output_options_ & OO_Tabular) && - (!internal::SameNames(run.counters, prev_counters_)); - if (print_header) { - printed_header_ = true; - prev_counters_ = run.counters; - PrintHeader(run); - } - // As an alternative to printing the headers like this, we could sort - // the benchmarks by header and then print. But this would require - // waiting for the full results before printing, or printing twice. - PrintRunData(run); - } -} - -static void IgnoreColorPrint(std::ostream& out, LogColor, const char* fmt, - ...) { - va_list args; - va_start(args, fmt); - out << FormatString(fmt, args); - va_end(args); -} - - -static std::string FormatTime(double time) { - // Align decimal places... - if (time < 1.0) { - return FormatString("%10.3f", time); - } - if (time < 10.0) { - return FormatString("%10.2f", time); - } - if (time < 100.0) { - return FormatString("%10.1f", time); - } - return FormatString("%10.0f", time); -} - -void ConsoleReporter::PrintRunData(const Run& result) { - typedef void(PrinterFn)(std::ostream&, LogColor, const char*, ...); - auto& Out = GetOutputStream(); - PrinterFn* printer = (output_options_ & OO_Color) ? - (PrinterFn*)ColorPrintf : IgnoreColorPrint; - auto name_color = - (result.report_big_o || result.report_rms) ? COLOR_BLUE : COLOR_GREEN; - printer(Out, name_color, "%-*s ", name_field_width_, - result.benchmark_name().c_str()); - - if (result.error_occurred) { - printer(Out, COLOR_RED, "ERROR OCCURRED: \'%s\'", - result.error_message.c_str()); - printer(Out, COLOR_DEFAULT, "\n"); - return; - } - - const double real_time = result.GetAdjustedRealTime(); - const double cpu_time = result.GetAdjustedCPUTime(); - const std::string real_time_str = FormatTime(real_time); - const std::string cpu_time_str = FormatTime(cpu_time); - - - if (result.report_big_o) { - std::string big_o = GetBigOString(result.complexity); - printer(Out, COLOR_YELLOW, "%10.2f %-4s %10.2f %-4s ", real_time, big_o.c_str(), - cpu_time, big_o.c_str()); - } else if (result.report_rms) { - printer(Out, COLOR_YELLOW, "%10.0f %-4s %10.0f %-4s ", real_time * 100, "%", - cpu_time * 100, "%"); - } else { - const char* timeLabel = GetTimeUnitString(result.time_unit); - printer(Out, COLOR_YELLOW, "%s %-4s %s %-4s ", real_time_str.c_str(), timeLabel, - cpu_time_str.c_str(), timeLabel); - } - - if (!result.report_big_o && !result.report_rms) { - printer(Out, COLOR_CYAN, "%10lld", result.iterations); - } - - for (auto& c : result.counters) { - const std::size_t cNameLen = std::max(std::string::size_type(10), - c.first.length()); - auto const& s = HumanReadableNumber(c.second.value, c.second.oneK); - if (output_options_ & OO_Tabular) { - if (c.second.flags & Counter::kIsRate) { - printer(Out, COLOR_DEFAULT, " %*s/s", cNameLen - 2, s.c_str()); - } else { - printer(Out, COLOR_DEFAULT, " %*s", cNameLen, s.c_str()); - } - } else { - const char* unit = (c.second.flags & Counter::kIsRate) ? "/s" : ""; - printer(Out, COLOR_DEFAULT, " %s=%s%s", c.first.c_str(), s.c_str(), - unit); - } - } - - if (!result.report_label.empty()) { - printer(Out, COLOR_DEFAULT, " %s", result.report_label.c_str()); - } - - printer(Out, COLOR_DEFAULT, "\n"); -} - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/counter.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/counter.cc deleted file mode 100644 index c248ea110bc..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/counter.cc +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "counter.h" - -namespace benchmark { -namespace internal { - -double Finish(Counter const& c, IterationCount iterations, double cpu_time, - double num_threads) { - double v = c.value; - if (c.flags & Counter::kIsRate) { - v /= cpu_time; - } - if (c.flags & Counter::kAvgThreads) { - v /= num_threads; - } - if (c.flags & Counter::kIsIterationInvariant) { - v *= iterations; - } - if (c.flags & Counter::kAvgIterations) { - v /= iterations; - } - return v; -} - -void Finish(UserCounters* l, IterationCount iterations, double cpu_time, - double num_threads) { - for (auto& c : *l) { - c.second.value = Finish(c.second, iterations, cpu_time, num_threads); - } -} - -void Increment(UserCounters* l, UserCounters const& r) { - // add counters present in both or just in *l - for (auto& c : *l) { - auto it = r.find(c.first); - if (it != r.end()) { - c.second.value = c.second + it->second; - } - } - // add counters present in r, but not in *l - for (auto const& tc : r) { - auto it = l->find(tc.first); - if (it == l->end()) { - (*l)[tc.first] = tc.second; - } - } -} - -bool SameNames(UserCounters const& l, UserCounters const& r) { - if (&l == &r) return true; - if (l.size() != r.size()) { - return false; - } - for (auto const& c : l) { - if (r.find(c.first) == r.end()) { - return false; - } - } - return true; -} - -} // end namespace internal -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/counter.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/counter.h deleted file mode 100644 index 1ad46d4940e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/counter.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" - -namespace benchmark { - -// these counter-related functions are hidden to reduce API surface. -namespace internal { -void Finish(UserCounters* l, IterationCount iterations, double time, - double num_threads); -void Increment(UserCounters* l, UserCounters const& r); -bool SameNames(UserCounters const& l, UserCounters const& r); -} // end namespace internal - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/csv_reporter.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/csv_reporter.cc deleted file mode 100644 index af2c18fc8a6..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/csv_reporter.cc +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "complexity.h" - -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "string_util.h" -#include "timers.h" - -// File format reference: http://edoceo.com/utilitas/csv-file-format. - -namespace benchmark { - -namespace { -std::vector elements = { - "name", "iterations", "real_time", "cpu_time", - "time_unit", "bytes_per_second", "items_per_second", "label", - "error_occurred", "error_message"}; -} // namespace - -std::string CsvEscape(const std::string & s) { - std::string tmp; - tmp.reserve(s.size() + 2); - for (char c : s) { - switch (c) { - case '"' : tmp += "\"\""; break; - default : tmp += c; break; - } - } - return '"' + tmp + '"'; -} - -bool CSVReporter::ReportContext(const Context& context) { - PrintBasicContext(&GetErrorStream(), context); - return true; -} - -void CSVReporter::ReportRuns(const std::vector& reports) { - std::ostream& Out = GetOutputStream(); - - if (!printed_header_) { - // save the names of all the user counters - for (const auto& run : reports) { - for (const auto& cnt : run.counters) { - if (cnt.first == "bytes_per_second" || cnt.first == "items_per_second") - continue; - user_counter_names_.insert(cnt.first); - } - } - - // print the header - for (auto B = elements.begin(); B != elements.end();) { - Out << *B++; - if (B != elements.end()) Out << ","; - } - for (auto B = user_counter_names_.begin(); - B != user_counter_names_.end();) { - Out << ",\"" << *B++ << "\""; - } - Out << "\n"; - - printed_header_ = true; - } else { - // check that all the current counters are saved in the name set - for (const auto& run : reports) { - for (const auto& cnt : run.counters) { - if (cnt.first == "bytes_per_second" || cnt.first == "items_per_second") - continue; - CHECK(user_counter_names_.find(cnt.first) != user_counter_names_.end()) - << "All counters must be present in each run. " - << "Counter named \"" << cnt.first - << "\" was not in a run after being added to the header"; - } - } - } - - // print results for each run - for (const auto& run : reports) { - PrintRunData(run); - } -} - -void CSVReporter::PrintRunData(const Run& run) { - std::ostream& Out = GetOutputStream(); - Out << CsvEscape(run.benchmark_name()) << ","; - if (run.error_occurred) { - Out << std::string(elements.size() - 3, ','); - Out << "true,"; - Out << CsvEscape(run.error_message) << "\n"; - return; - } - - // Do not print iteration on bigO and RMS report - if (!run.report_big_o && !run.report_rms) { - Out << run.iterations; - } - Out << ","; - - Out << run.GetAdjustedRealTime() << ","; - Out << run.GetAdjustedCPUTime() << ","; - - // Do not print timeLabel on bigO and RMS report - if (run.report_big_o) { - Out << GetBigOString(run.complexity); - } else if (!run.report_rms) { - Out << GetTimeUnitString(run.time_unit); - } - Out << ","; - - if (run.counters.find("bytes_per_second") != run.counters.end()) { - Out << run.counters.at("bytes_per_second"); - } - Out << ","; - if (run.counters.find("items_per_second") != run.counters.end()) { - Out << run.counters.at("items_per_second"); - } - Out << ","; - if (!run.report_label.empty()) { - Out << CsvEscape(run.report_label); - } - Out << ",,"; // for error_occurred and error_message - - // Print user counters - for (const auto& ucn : user_counter_names_) { - auto it = run.counters.find(ucn); - if (it == run.counters.end()) { - Out << ","; - } else { - Out << "," << it->second; - } - } - Out << '\n'; -} - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/cycleclock.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/cycleclock.h deleted file mode 100644 index f5e37b011b9..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/cycleclock.h +++ /dev/null @@ -1,177 +0,0 @@ -// ---------------------------------------------------------------------- -// CycleClock -// A CycleClock tells you the current time in Cycles. The "time" -// is actually time since power-on. This is like time() but doesn't -// involve a system call and is much more precise. -// -// NOTE: Not all cpu/platform/kernel combinations guarantee that this -// clock increments at a constant rate or is synchronized across all logical -// cpus in a system. -// -// If you need the above guarantees, please consider using a different -// API. There are efforts to provide an interface which provides a millisecond -// granularity and implemented as a memory read. A memory read is generally -// cheaper than the CycleClock for many architectures. -// -// Also, in some out of order CPU implementations, the CycleClock is not -// serializing. So if you're trying to count at cycles granularity, your -// data might be inaccurate due to out of order instruction execution. -// ---------------------------------------------------------------------- - -#ifndef BENCHMARK_CYCLECLOCK_H_ -#define BENCHMARK_CYCLECLOCK_H_ - -#include - -#include "benchmark/benchmark.h" -#include "internal_macros.h" - -#if defined(BENCHMARK_OS_MACOSX) -#include -#endif -// For MSVC, we want to use '_asm rdtsc' when possible (since it works -// with even ancient MSVC compilers), and when not possible the -// __rdtsc intrinsic, declared in . Unfortunately, in some -// environments, and have conflicting -// declarations of some other intrinsics, breaking compilation. -// Therefore, we simply declare __rdtsc ourselves. See also -// http://connect.microsoft.com/VisualStudio/feedback/details/262047 -#if defined(COMPILER_MSVC) && !defined(_M_IX86) -extern "C" uint64_t __rdtsc(); -#pragma intrinsic(__rdtsc) -#endif - -#if !defined(BENCHMARK_OS_WINDOWS) || defined(BENCHMARK_OS_MINGW) -#include -#include -#endif - -#ifdef BENCHMARK_OS_EMSCRIPTEN -#include -#endif - -namespace benchmark { -// NOTE: only i386 and x86_64 have been well tested. -// PPC, sparc, alpha, and ia64 are based on -// http://peter.kuscsik.com/wordpress/?p=14 -// with modifications by m3b. See also -// https://setisvn.ssl.berkeley.edu/svn/lib/fftw-3.0.1/kernel/cycle.h -namespace cycleclock { -// This should return the number of cycles since power-on. Thread-safe. -inline BENCHMARK_ALWAYS_INLINE int64_t Now() { -#if defined(BENCHMARK_OS_MACOSX) - // this goes at the top because we need ALL Macs, regardless of - // architecture, to return the number of "mach time units" that - // have passed since startup. See sysinfo.cc where - // InitializeSystemInfo() sets the supposed cpu clock frequency of - // macs to the number of mach time units per second, not actual - // CPU clock frequency (which can change in the face of CPU - // frequency scaling). Also note that when the Mac sleeps, this - // counter pauses; it does not continue counting, nor does it - // reset to zero. - return mach_absolute_time(); -#elif defined(BENCHMARK_OS_EMSCRIPTEN) - // this goes above x86-specific code because old versions of Emscripten - // define __x86_64__, although they have nothing to do with it. - return static_cast(emscripten_get_now() * 1e+6); -#elif defined(__i386__) - int64_t ret; - __asm__ volatile("rdtsc" : "=A"(ret)); - return ret; -#elif defined(__x86_64__) || defined(__amd64__) - uint64_t low, high; - __asm__ volatile("rdtsc" : "=a"(low), "=d"(high)); - return (high << 32) | low; -#elif defined(__powerpc__) || defined(__ppc__) - // This returns a time-base, which is not always precisely a cycle-count. - int64_t tbl, tbu0, tbu1; - asm("mftbu %0" : "=r"(tbu0)); - asm("mftb %0" : "=r"(tbl)); - asm("mftbu %0" : "=r"(tbu1)); - tbl &= -static_cast(tbu0 == tbu1); - // high 32 bits in tbu1; low 32 bits in tbl (tbu0 is garbage) - return (tbu1 << 32) | tbl; -#elif defined(__sparc__) - int64_t tick; - asm(".byte 0x83, 0x41, 0x00, 0x00"); - asm("mov %%g1, %0" : "=r"(tick)); - return tick; -#elif defined(__ia64__) - int64_t itc; - asm("mov %0 = ar.itc" : "=r"(itc)); - return itc; -#elif defined(COMPILER_MSVC) && defined(_M_IX86) - // Older MSVC compilers (like 7.x) don't seem to support the - // __rdtsc intrinsic properly, so I prefer to use _asm instead - // when I know it will work. Otherwise, I'll use __rdtsc and hope - // the code is being compiled with a non-ancient compiler. - _asm rdtsc -#elif defined(COMPILER_MSVC) - return __rdtsc(); -#elif defined(BENCHMARK_OS_NACL) - // Native Client validator on x86/x86-64 allows RDTSC instructions, - // and this case is handled above. Native Client validator on ARM - // rejects MRC instructions (used in the ARM-specific sequence below), - // so we handle it here. Portable Native Client compiles to - // architecture-agnostic bytecode, which doesn't provide any - // cycle counter access mnemonics. - - // Native Client does not provide any API to access cycle counter. - // Use clock_gettime(CLOCK_MONOTONIC, ...) instead of gettimeofday - // because is provides nanosecond resolution (which is noticable at - // least for PNaCl modules running on x86 Mac & Linux). - // Initialize to always return 0 if clock_gettime fails. - struct timespec ts = {0, 0}; - clock_gettime(CLOCK_MONOTONIC, &ts); - return static_cast(ts.tv_sec) * 1000000000 + ts.tv_nsec; -#elif defined(__aarch64__) - // System timer of ARMv8 runs at a different frequency than the CPU's. - // The frequency is fixed, typically in the range 1-50MHz. It can be - // read at CNTFRQ special register. We assume the OS has set up - // the virtual timer properly. - int64_t virtual_timer_value; - asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value)); - return virtual_timer_value; -#elif defined(__ARM_ARCH) - // V6 is the earliest arch that has a standard cyclecount - // Native Client validator doesn't allow MRC instructions. -#if (__ARM_ARCH >= 6) - uint32_t pmccntr; - uint32_t pmuseren; - uint32_t pmcntenset; - // Read the user mode perf monitor counter access permissions. - asm volatile("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren)); - if (pmuseren & 1) { // Allows reading perfmon counters for user mode code. - asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset)); - if (pmcntenset & 0x80000000ul) { // Is it counting? - asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr)); - // The counter is set up to count every 64th cycle - return static_cast(pmccntr) * 64; // Should optimize to << 6 - } - } -#endif - struct timeval tv; - gettimeofday(&tv, nullptr); - return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; -#elif defined(__mips__) - // mips apparently only allows rdtsc for superusers, so we fall - // back to gettimeofday. It's possible clock_gettime would be better. - struct timeval tv; - gettimeofday(&tv, nullptr); - return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; -#elif defined(__s390__) // Covers both s390 and s390x. - // Return the CPU clock. - uint64_t tsc; - asm("stck %0" : "=Q"(tsc) : : "cc"); - return tsc; -#else -// The soft failover to a generic implementation is automatic only for ARM. -// For other platforms the developer is expected to make an attempt to create -// a fast implementation and use generic version if nothing better is available. -#error You need to define CycleTimer for your OS and CPU -#endif -} -} // end namespace cycleclock -} // end namespace benchmark - -#endif // BENCHMARK_CYCLECLOCK_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/internal_macros.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/internal_macros.h deleted file mode 100644 index 6adf00d0569..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/internal_macros.h +++ /dev/null @@ -1,94 +0,0 @@ -#ifndef BENCHMARK_INTERNAL_MACROS_H_ -#define BENCHMARK_INTERNAL_MACROS_H_ - -#include "benchmark/benchmark.h" - -/* Needed to detect STL */ -#include - -// clang-format off - -#ifndef __has_feature -#define __has_feature(x) 0 -#endif - -#if defined(__clang__) - #if !defined(COMPILER_CLANG) - #define COMPILER_CLANG - #endif -#elif defined(_MSC_VER) - #if !defined(COMPILER_MSVC) - #define COMPILER_MSVC - #endif -#elif defined(__GNUC__) - #if !defined(COMPILER_GCC) - #define COMPILER_GCC - #endif -#endif - -#if __has_feature(cxx_attributes) - #define BENCHMARK_NORETURN [[noreturn]] -#elif defined(__GNUC__) - #define BENCHMARK_NORETURN __attribute__((noreturn)) -#elif defined(COMPILER_MSVC) - #define BENCHMARK_NORETURN __declspec(noreturn) -#else - #define BENCHMARK_NORETURN -#endif - -#if defined(__CYGWIN__) - #define BENCHMARK_OS_CYGWIN 1 -#elif defined(_WIN32) - #define BENCHMARK_OS_WINDOWS 1 - #if defined(__MINGW32__) - #define BENCHMARK_OS_MINGW 1 - #endif -#elif defined(__APPLE__) - #define BENCHMARK_OS_APPLE 1 - #include "TargetConditionals.h" - #if defined(TARGET_OS_MAC) - #define BENCHMARK_OS_MACOSX 1 - #if defined(TARGET_OS_IPHONE) - #define BENCHMARK_OS_IOS 1 - #endif - #endif -#elif defined(__FreeBSD__) - #define BENCHMARK_OS_FREEBSD 1 -#elif defined(__NetBSD__) - #define BENCHMARK_OS_NETBSD 1 -#elif defined(__OpenBSD__) - #define BENCHMARK_OS_OPENBSD 1 -#elif defined(__linux__) - #define BENCHMARK_OS_LINUX 1 -#elif defined(__native_client__) - #define BENCHMARK_OS_NACL 1 -#elif defined(__EMSCRIPTEN__) - #define BENCHMARK_OS_EMSCRIPTEN 1 -#elif defined(__rtems__) - #define BENCHMARK_OS_RTEMS 1 -#elif defined(__Fuchsia__) -#define BENCHMARK_OS_FUCHSIA 1 -#elif defined (__SVR4) && defined (__sun) -#define BENCHMARK_OS_SOLARIS 1 -#elif defined(__QNX__) -#define BENCHMARK_OS_QNX 1 -#endif - -#if defined(__ANDROID__) && defined(__GLIBCXX__) -#define BENCHMARK_STL_ANDROID_GNUSTL 1 -#endif - -#if !__has_feature(cxx_exceptions) && !defined(__cpp_exceptions) \ - && !defined(__EXCEPTIONS) - #define BENCHMARK_HAS_NO_EXCEPTIONS -#endif - -#if defined(COMPILER_CLANG) || defined(COMPILER_GCC) - #define BENCHMARK_MAYBE_UNUSED __attribute__((unused)) -#else - #define BENCHMARK_MAYBE_UNUSED -#endif - -// clang-format on - -#endif // BENCHMARK_INTERNAL_MACROS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/json_reporter.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/json_reporter.cc deleted file mode 100644 index 11db2b99d50..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/json_reporter.cc +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "complexity.h" - -#include -#include -#include -#include // for setprecision -#include -#include -#include -#include -#include - -#include "string_util.h" -#include "timers.h" - -namespace benchmark { - -namespace { - -std::string StrEscape(const std::string & s) { - std::string tmp; - tmp.reserve(s.size()); - for (char c : s) { - switch (c) { - case '\b': tmp += "\\b"; break; - case '\f': tmp += "\\f"; break; - case '\n': tmp += "\\n"; break; - case '\r': tmp += "\\r"; break; - case '\t': tmp += "\\t"; break; - case '\\': tmp += "\\\\"; break; - case '"' : tmp += "\\\""; break; - default : tmp += c; break; - } - } - return tmp; -} - -std::string FormatKV(std::string const& key, std::string const& value) { - return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(), StrEscape(value).c_str()); -} - -std::string FormatKV(std::string const& key, const char* value) { - return StrFormat("\"%s\": \"%s\"", StrEscape(key).c_str(), StrEscape(value).c_str()); -} - -std::string FormatKV(std::string const& key, bool value) { - return StrFormat("\"%s\": %s", StrEscape(key).c_str(), value ? "true" : "false"); -} - -std::string FormatKV(std::string const& key, int64_t value) { - std::stringstream ss; - ss << '"' << StrEscape(key) << "\": " << value; - return ss.str(); -} - -std::string FormatKV(std::string const& key, IterationCount value) { - std::stringstream ss; - ss << '"' << StrEscape(key) << "\": " << value; - return ss.str(); -} - -std::string FormatKV(std::string const& key, double value) { - std::stringstream ss; - ss << '"' << StrEscape(key) << "\": "; - - if (std::isnan(value)) - ss << (value < 0 ? "-" : "") << "NaN"; - else if (std::isinf(value)) - ss << (value < 0 ? "-" : "") << "Infinity"; - else { - const auto max_digits10 = - std::numeric_limits::max_digits10; - const auto max_fractional_digits10 = max_digits10 - 1; - ss << std::scientific << std::setprecision(max_fractional_digits10) - << value; - } - return ss.str(); -} - -int64_t RoundDouble(double v) { return static_cast(v + 0.5); } - -} // end namespace - -bool JSONReporter::ReportContext(const Context& context) { - std::ostream& out = GetOutputStream(); - - out << "{\n"; - std::string inner_indent(2, ' '); - - // Open context block and print context information. - out << inner_indent << "\"context\": {\n"; - std::string indent(4, ' '); - - std::string walltime_value = LocalDateTimeString(); - out << indent << FormatKV("date", walltime_value) << ",\n"; - - out << indent << FormatKV("host_name", context.sys_info.name) << ",\n"; - - if (Context::executable_name) { - out << indent << FormatKV("executable", Context::executable_name) << ",\n"; - } - - CPUInfo const& info = context.cpu_info; - out << indent << FormatKV("num_cpus", static_cast(info.num_cpus)) - << ",\n"; - out << indent - << FormatKV("mhz_per_cpu", - RoundDouble(info.cycles_per_second / 1000000.0)) - << ",\n"; - out << indent << FormatKV("cpu_scaling_enabled", info.scaling_enabled) - << ",\n"; - - out << indent << "\"caches\": [\n"; - indent = std::string(6, ' '); - std::string cache_indent(8, ' '); - for (size_t i = 0; i < info.caches.size(); ++i) { - auto& CI = info.caches[i]; - out << indent << "{\n"; - out << cache_indent << FormatKV("type", CI.type) << ",\n"; - out << cache_indent << FormatKV("level", static_cast(CI.level)) - << ",\n"; - out << cache_indent - << FormatKV("size", static_cast(CI.size) * 1000u) << ",\n"; - out << cache_indent - << FormatKV("num_sharing", static_cast(CI.num_sharing)) - << "\n"; - out << indent << "}"; - if (i != info.caches.size() - 1) out << ","; - out << "\n"; - } - indent = std::string(4, ' '); - out << indent << "],\n"; - out << indent << "\"load_avg\": ["; - for (auto it = info.load_avg.begin(); it != info.load_avg.end();) { - out << *it++; - if (it != info.load_avg.end()) out << ","; - } - out << "],\n"; - -#if defined(NDEBUG) - const char build_type[] = "release"; -#else - const char build_type[] = "debug"; -#endif - out << indent << FormatKV("library_build_type", build_type) << "\n"; - // Close context block and open the list of benchmarks. - out << inner_indent << "},\n"; - out << inner_indent << "\"benchmarks\": [\n"; - return true; -} - -void JSONReporter::ReportRuns(std::vector const& reports) { - if (reports.empty()) { - return; - } - std::string indent(4, ' '); - std::ostream& out = GetOutputStream(); - if (!first_report_) { - out << ",\n"; - } - first_report_ = false; - - for (auto it = reports.begin(); it != reports.end(); ++it) { - out << indent << "{\n"; - PrintRunData(*it); - out << indent << '}'; - auto it_cp = it; - if (++it_cp != reports.end()) { - out << ",\n"; - } - } -} - -void JSONReporter::Finalize() { - // Close the list of benchmarks and the top level object. - GetOutputStream() << "\n ]\n}\n"; -} - -void JSONReporter::PrintRunData(Run const& run) { - std::string indent(6, ' '); - std::ostream& out = GetOutputStream(); - out << indent << FormatKV("name", run.benchmark_name()) << ",\n"; - out << indent << FormatKV("run_name", run.run_name.str()) << ",\n"; - out << indent << FormatKV("run_type", [&run]() -> const char* { - switch (run.run_type) { - case BenchmarkReporter::Run::RT_Iteration: - return "iteration"; - case BenchmarkReporter::Run::RT_Aggregate: - return "aggregate"; - } - BENCHMARK_UNREACHABLE(); - }()) << ",\n"; - out << indent << FormatKV("repetitions", run.repetitions) << ",\n"; - if (run.run_type != BenchmarkReporter::Run::RT_Aggregate) { - out << indent << FormatKV("repetition_index", run.repetition_index) - << ",\n"; - } - out << indent << FormatKV("threads", run.threads) << ",\n"; - if (run.run_type == BenchmarkReporter::Run::RT_Aggregate) { - out << indent << FormatKV("aggregate_name", run.aggregate_name) << ",\n"; - } - if (run.error_occurred) { - out << indent << FormatKV("error_occurred", run.error_occurred) << ",\n"; - out << indent << FormatKV("error_message", run.error_message) << ",\n"; - } - if (!run.report_big_o && !run.report_rms) { - out << indent << FormatKV("iterations", run.iterations) << ",\n"; - out << indent << FormatKV("real_time", run.GetAdjustedRealTime()) << ",\n"; - out << indent << FormatKV("cpu_time", run.GetAdjustedCPUTime()); - out << ",\n" - << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit)); - } else if (run.report_big_o) { - out << indent << FormatKV("cpu_coefficient", run.GetAdjustedCPUTime()) - << ",\n"; - out << indent << FormatKV("real_coefficient", run.GetAdjustedRealTime()) - << ",\n"; - out << indent << FormatKV("big_o", GetBigOString(run.complexity)) << ",\n"; - out << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit)); - } else if (run.report_rms) { - out << indent << FormatKV("rms", run.GetAdjustedCPUTime()); - } - - for (auto& c : run.counters) { - out << ",\n" << indent << FormatKV(c.first, c.second); - } - - if (run.has_memory_result) { - out << ",\n" << indent << FormatKV("allocs_per_iter", run.allocs_per_iter); - out << ",\n" << indent << FormatKV("max_bytes_used", run.max_bytes_used); - } - - if (!run.report_label.empty()) { - out << ",\n" << indent << FormatKV("label", run.report_label); - } - out << '\n'; -} - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/log.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/log.h deleted file mode 100644 index 47d0c35c018..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/log.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef BENCHMARK_LOG_H_ -#define BENCHMARK_LOG_H_ - -#include -#include - -#include "benchmark/benchmark.h" - -namespace benchmark { -namespace internal { - -typedef std::basic_ostream&(EndLType)(std::basic_ostream&); - -class LogType { - friend LogType& GetNullLogInstance(); - friend LogType& GetErrorLogInstance(); - - // FIXME: Add locking to output. - template - friend LogType& operator<<(LogType&, Tp const&); - friend LogType& operator<<(LogType&, EndLType*); - - private: - LogType(std::ostream* out) : out_(out) {} - std::ostream* out_; - BENCHMARK_DISALLOW_COPY_AND_ASSIGN(LogType); -}; - -template -LogType& operator<<(LogType& log, Tp const& value) { - if (log.out_) { - *log.out_ << value; - } - return log; -} - -inline LogType& operator<<(LogType& log, EndLType* m) { - if (log.out_) { - *log.out_ << m; - } - return log; -} - -inline int& LogLevel() { - static int log_level = 0; - return log_level; -} - -inline LogType& GetNullLogInstance() { - static LogType log(nullptr); - return log; -} - -inline LogType& GetErrorLogInstance() { - static LogType log(&std::clog); - return log; -} - -inline LogType& GetLogInstanceForLevel(int level) { - if (level <= LogLevel()) { - return GetErrorLogInstance(); - } - return GetNullLogInstance(); -} - -} // end namespace internal -} // end namespace benchmark - -// clang-format off -#define VLOG(x) \ - (::benchmark::internal::GetLogInstanceForLevel(x) << "-- LOG(" << x << "):" \ - " ") -// clang-format on -#endif diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/mutex.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/mutex.h deleted file mode 100644 index 5f461d05a0c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/mutex.h +++ /dev/null @@ -1,155 +0,0 @@ -#ifndef BENCHMARK_MUTEX_H_ -#define BENCHMARK_MUTEX_H_ - -#include -#include - -#include "check.h" - -// Enable thread safety attributes only with clang. -// The attributes can be safely erased when compiling with other compilers. -#if defined(HAVE_THREAD_SAFETY_ATTRIBUTES) -#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) -#else -#define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op -#endif - -#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) - -#define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) - -#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) - -#define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) - -#define ACQUIRED_BEFORE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__)) - -#define ACQUIRED_AFTER(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__)) - -#define REQUIRES(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) - -#define REQUIRES_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) - -#define ACQUIRE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) - -#define ACQUIRE_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__)) - -#define RELEASE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__)) - -#define RELEASE_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__)) - -#define TRY_ACQUIRE(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__)) - -#define TRY_ACQUIRE_SHARED(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__)) - -#define EXCLUDES(...) THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) - -#define ASSERT_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) - -#define ASSERT_SHARED_CAPABILITY(x) \ - THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x)) - -#define RETURN_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) - -#define NO_THREAD_SAFETY_ANALYSIS \ - THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) - -namespace benchmark { - -typedef std::condition_variable Condition; - -// NOTE: Wrappers for std::mutex and std::unique_lock are provided so that -// we can annotate them with thread safety attributes and use the -// -Wthread-safety warning with clang. The standard library types cannot be -// used directly because they do not provided the required annotations. -class CAPABILITY("mutex") Mutex { - public: - Mutex() {} - - void lock() ACQUIRE() { mut_.lock(); } - void unlock() RELEASE() { mut_.unlock(); } - std::mutex& native_handle() { return mut_; } - - private: - std::mutex mut_; -}; - -class SCOPED_CAPABILITY MutexLock { - typedef std::unique_lock MutexLockImp; - - public: - MutexLock(Mutex& m) ACQUIRE(m) : ml_(m.native_handle()) {} - ~MutexLock() RELEASE() {} - MutexLockImp& native_handle() { return ml_; } - - private: - MutexLockImp ml_; -}; - -class Barrier { - public: - Barrier(int num_threads) : running_threads_(num_threads) {} - - // Called by each thread - bool wait() EXCLUDES(lock_) { - bool last_thread = false; - { - MutexLock ml(lock_); - last_thread = createBarrier(ml); - } - if (last_thread) phase_condition_.notify_all(); - return last_thread; - } - - void removeThread() EXCLUDES(lock_) { - MutexLock ml(lock_); - --running_threads_; - if (entered_ != 0) phase_condition_.notify_all(); - } - - private: - Mutex lock_; - Condition phase_condition_; - int running_threads_; - - // State for barrier management - int phase_number_ = 0; - int entered_ = 0; // Number of threads that have entered this barrier - - // Enter the barrier and wait until all other threads have also - // entered the barrier. Returns iff this is the last thread to - // enter the barrier. - bool createBarrier(MutexLock& ml) REQUIRES(lock_) { - CHECK_LT(entered_, running_threads_); - entered_++; - if (entered_ < running_threads_) { - // Wait for all threads to enter - int phase_number_cp = phase_number_; - auto cb = [this, phase_number_cp]() { - return this->phase_number_ > phase_number_cp || - entered_ == running_threads_; // A thread has aborted in error - }; - phase_condition_.wait(ml.native_handle(), cb); - if (phase_number_ > phase_number_cp) return false; - // else (running_threads_ == entered_) and we are the last thread. - } - // Last thread has reached the barrier - phase_number_++; - entered_ = 0; - return true; - } -}; - -} // end namespace benchmark - -#endif // BENCHMARK_MUTEX_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/re.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/re.h deleted file mode 100644 index fbe25037b46..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/re.h +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef BENCHMARK_RE_H_ -#define BENCHMARK_RE_H_ - -#include "internal_macros.h" - -// clang-format off - -#if !defined(HAVE_STD_REGEX) && \ - !defined(HAVE_GNU_POSIX_REGEX) && \ - !defined(HAVE_POSIX_REGEX) - // No explicit regex selection; detect based on builtin hints. - #if defined(BENCHMARK_OS_LINUX) || defined(BENCHMARK_OS_APPLE) - #define HAVE_POSIX_REGEX 1 - #elif __cplusplus >= 199711L - #define HAVE_STD_REGEX 1 - #endif -#endif - -// Prefer C regex libraries when compiling w/o exceptions so that we can -// correctly report errors. -#if defined(BENCHMARK_HAS_NO_EXCEPTIONS) && \ - defined(BENCHMARK_HAVE_STD_REGEX) && \ - (defined(HAVE_GNU_POSIX_REGEX) || defined(HAVE_POSIX_REGEX)) - #undef HAVE_STD_REGEX -#endif - -#if defined(HAVE_STD_REGEX) - #include -#elif defined(HAVE_GNU_POSIX_REGEX) - #include -#elif defined(HAVE_POSIX_REGEX) - #include -#else -#error No regular expression backend was found! -#endif - -// clang-format on - -#include - -#include "check.h" - -namespace benchmark { - -// A wrapper around the POSIX regular expression API that provides automatic -// cleanup -class Regex { - public: - Regex() : init_(false) {} - - ~Regex(); - - // Compile a regular expression matcher from spec. Returns true on success. - // - // On failure (and if error is not nullptr), error is populated with a human - // readable error message if an error occurs. - bool Init(const std::string& spec, std::string* error); - - // Returns whether str matches the compiled regular expression. - bool Match(const std::string& str); - - private: - bool init_; -// Underlying regular expression object -#if defined(HAVE_STD_REGEX) - std::regex re_; -#elif defined(HAVE_POSIX_REGEX) || defined(HAVE_GNU_POSIX_REGEX) - regex_t re_; -#else -#error No regular expression backend implementation available -#endif -}; - -#if defined(HAVE_STD_REGEX) - -inline bool Regex::Init(const std::string& spec, std::string* error) { -#ifdef BENCHMARK_HAS_NO_EXCEPTIONS - ((void)error); // suppress unused warning -#else - try { -#endif - re_ = std::regex(spec, std::regex_constants::extended); - init_ = true; -#ifndef BENCHMARK_HAS_NO_EXCEPTIONS -} -catch (const std::regex_error& e) { - if (error) { - *error = e.what(); - } -} -#endif -return init_; -} - -inline Regex::~Regex() {} - -inline bool Regex::Match(const std::string& str) { - if (!init_) { - return false; - } - return std::regex_search(str, re_); -} - -#else -inline bool Regex::Init(const std::string& spec, std::string* error) { - int ec = regcomp(&re_, spec.c_str(), REG_EXTENDED | REG_NOSUB); - if (ec != 0) { - if (error) { - size_t needed = regerror(ec, &re_, nullptr, 0); - char* errbuf = new char[needed]; - regerror(ec, &re_, errbuf, needed); - - // regerror returns the number of bytes necessary to null terminate - // the string, so we move that when assigning to error. - CHECK_NE(needed, 0); - error->assign(errbuf, needed - 1); - - delete[] errbuf; - } - - return false; - } - - init_ = true; - return true; -} - -inline Regex::~Regex() { - if (init_) { - regfree(&re_); - } -} - -inline bool Regex::Match(const std::string& str) { - if (!init_) { - return false; - } - return regexec(&re_, str.c_str(), 0, nullptr, 0) == 0; -} -#endif - -} // end namespace benchmark - -#endif // BENCHMARK_RE_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/reporter.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/reporter.cc deleted file mode 100644 index 4d3e477d44a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/reporter.cc +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" -#include "timers.h" - -#include - -#include -#include -#include - -#include "check.h" -#include "string_util.h" - -namespace benchmark { - -BenchmarkReporter::BenchmarkReporter() - : output_stream_(&std::cout), error_stream_(&std::cerr) {} - -BenchmarkReporter::~BenchmarkReporter() {} - -void BenchmarkReporter::PrintBasicContext(std::ostream *out, - Context const &context) { - CHECK(out) << "cannot be null"; - auto &Out = *out; - - Out << LocalDateTimeString() << "\n"; - - if (context.executable_name) - Out << "Running " << context.executable_name << "\n"; - - const CPUInfo &info = context.cpu_info; - Out << "Run on (" << info.num_cpus << " X " - << (info.cycles_per_second / 1000000.0) << " MHz CPU " - << ((info.num_cpus > 1) ? "s" : "") << ")\n"; - if (info.caches.size() != 0) { - Out << "CPU Caches:\n"; - for (auto &CInfo : info.caches) { - Out << " L" << CInfo.level << " " << CInfo.type << " " - << (CInfo.size / 1000) << "K"; - if (CInfo.num_sharing != 0) - Out << " (x" << (info.num_cpus / CInfo.num_sharing) << ")"; - Out << "\n"; - } - } - if (!info.load_avg.empty()) { - Out << "Load Average: "; - for (auto It = info.load_avg.begin(); It != info.load_avg.end();) { - Out << StrFormat("%.2f", *It++); - if (It != info.load_avg.end()) Out << ", "; - } - Out << "\n"; - } - - if (info.scaling_enabled) { - Out << "***WARNING*** CPU scaling is enabled, the benchmark " - "real time measurements may be noisy and will incur extra " - "overhead.\n"; - } - -#ifndef NDEBUG - Out << "***WARNING*** Library was built as DEBUG. Timings may be " - "affected.\n"; -#endif -} - -// No initializer because it's already initialized to NULL. -const char *BenchmarkReporter::Context::executable_name; - -BenchmarkReporter::Context::Context() - : cpu_info(CPUInfo::Get()), sys_info(SystemInfo::Get()) {} - -std::string BenchmarkReporter::Run::benchmark_name() const { - std::string name = run_name.str(); - if (run_type == RT_Aggregate) { - name += "_" + aggregate_name; - } - return name; -} - -double BenchmarkReporter::Run::GetAdjustedRealTime() const { - double new_time = real_accumulated_time * GetTimeUnitMultiplier(time_unit); - if (iterations != 0) new_time /= static_cast(iterations); - return new_time; -} - -double BenchmarkReporter::Run::GetAdjustedCPUTime() const { - double new_time = cpu_accumulated_time * GetTimeUnitMultiplier(time_unit); - if (iterations != 0) new_time /= static_cast(iterations); - return new_time; -} - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/sleep.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/sleep.cc deleted file mode 100644 index 1512ac90f7e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/sleep.cc +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "sleep.h" - -#include -#include -#include - -#include "internal_macros.h" - -#ifdef BENCHMARK_OS_WINDOWS -#include -#endif - -namespace benchmark { -#ifdef BENCHMARK_OS_WINDOWS -// Window's Sleep takes milliseconds argument. -void SleepForMilliseconds(int milliseconds) { Sleep(milliseconds); } -void SleepForSeconds(double seconds) { - SleepForMilliseconds(static_cast(kNumMillisPerSecond * seconds)); -} -#else // BENCHMARK_OS_WINDOWS -void SleepForMicroseconds(int microseconds) { - struct timespec sleep_time; - sleep_time.tv_sec = microseconds / kNumMicrosPerSecond; - sleep_time.tv_nsec = (microseconds % kNumMicrosPerSecond) * kNumNanosPerMicro; - while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) - ; // Ignore signals and wait for the full interval to elapse. -} - -void SleepForMilliseconds(int milliseconds) { - SleepForMicroseconds(milliseconds * kNumMicrosPerMilli); -} - -void SleepForSeconds(double seconds) { - SleepForMicroseconds(static_cast(seconds * kNumMicrosPerSecond)); -} -#endif // BENCHMARK_OS_WINDOWS -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/sleep.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/sleep.h deleted file mode 100644 index f98551afe28..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/sleep.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef BENCHMARK_SLEEP_H_ -#define BENCHMARK_SLEEP_H_ - -namespace benchmark { -const int kNumMillisPerSecond = 1000; -const int kNumMicrosPerMilli = 1000; -const int kNumMicrosPerSecond = kNumMillisPerSecond * 1000; -const int kNumNanosPerMicro = 1000; -const int kNumNanosPerSecond = kNumNanosPerMicro * kNumMicrosPerSecond; - -void SleepForMilliseconds(int milliseconds); -void SleepForSeconds(double seconds); -} // end namespace benchmark - -#endif // BENCHMARK_SLEEP_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/statistics.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/statistics.cc deleted file mode 100644 index bd5a3d65972..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/statistics.cc +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. -// Copyright 2017 Roman Lebedev. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "benchmark/benchmark.h" - -#include -#include -#include -#include -#include -#include "check.h" -#include "statistics.h" - -namespace benchmark { - -auto StatisticsSum = [](const std::vector& v) { - return std::accumulate(v.begin(), v.end(), 0.0); -}; - -double StatisticsMean(const std::vector& v) { - if (v.empty()) return 0.0; - return StatisticsSum(v) * (1.0 / v.size()); -} - -double StatisticsMedian(const std::vector& v) { - if (v.size() < 3) return StatisticsMean(v); - std::vector copy(v); - - auto center = copy.begin() + v.size() / 2; - std::nth_element(copy.begin(), center, copy.end()); - - // did we have an odd number of samples? - // if yes, then center is the median - // it no, then we are looking for the average between center and the value - // before - if (v.size() % 2 == 1) return *center; - auto center2 = copy.begin() + v.size() / 2 - 1; - std::nth_element(copy.begin(), center2, copy.end()); - return (*center + *center2) / 2.0; -} - -// Return the sum of the squares of this sample set -auto SumSquares = [](const std::vector& v) { - return std::inner_product(v.begin(), v.end(), v.begin(), 0.0); -}; - -auto Sqr = [](const double dat) { return dat * dat; }; -auto Sqrt = [](const double dat) { - // Avoid NaN due to imprecision in the calculations - if (dat < 0.0) return 0.0; - return std::sqrt(dat); -}; - -double StatisticsStdDev(const std::vector& v) { - const auto mean = StatisticsMean(v); - if (v.empty()) return mean; - - // Sample standard deviation is undefined for n = 1 - if (v.size() == 1) return 0.0; - - const double avg_squares = SumSquares(v) * (1.0 / v.size()); - return Sqrt(v.size() / (v.size() - 1.0) * (avg_squares - Sqr(mean))); -} - -std::vector ComputeStats( - const std::vector& reports) { - typedef BenchmarkReporter::Run Run; - std::vector results; - - auto error_count = - std::count_if(reports.begin(), reports.end(), - [](Run const& run) { return run.error_occurred; }); - - if (reports.size() - error_count < 2) { - // We don't report aggregated data if there was a single run. - return results; - } - - // Accumulators. - std::vector real_accumulated_time_stat; - std::vector cpu_accumulated_time_stat; - - real_accumulated_time_stat.reserve(reports.size()); - cpu_accumulated_time_stat.reserve(reports.size()); - - // All repetitions should be run with the same number of iterations so we - // can take this information from the first benchmark. - const IterationCount run_iterations = reports.front().iterations; - // create stats for user counters - struct CounterStat { - Counter c; - std::vector s; - }; - std::map counter_stats; - for (Run const& r : reports) { - for (auto const& cnt : r.counters) { - auto it = counter_stats.find(cnt.first); - if (it == counter_stats.end()) { - counter_stats.insert({cnt.first, {cnt.second, std::vector{}}}); - it = counter_stats.find(cnt.first); - it->second.s.reserve(reports.size()); - } else { - CHECK_EQ(counter_stats[cnt.first].c.flags, cnt.second.flags); - } - } - } - - // Populate the accumulators. - for (Run const& run : reports) { - CHECK_EQ(reports[0].benchmark_name(), run.benchmark_name()); - CHECK_EQ(run_iterations, run.iterations); - if (run.error_occurred) continue; - real_accumulated_time_stat.emplace_back(run.real_accumulated_time); - cpu_accumulated_time_stat.emplace_back(run.cpu_accumulated_time); - // user counters - for (auto const& cnt : run.counters) { - auto it = counter_stats.find(cnt.first); - CHECK_NE(it, counter_stats.end()); - it->second.s.emplace_back(cnt.second); - } - } - - // Only add label if it is same for all runs - std::string report_label = reports[0].report_label; - for (std::size_t i = 1; i < reports.size(); i++) { - if (reports[i].report_label != report_label) { - report_label = ""; - break; - } - } - - const double iteration_rescale_factor = - double(reports.size()) / double(run_iterations); - - for (const auto& Stat : *reports[0].statistics) { - // Get the data from the accumulator to BenchmarkReporter::Run's. - Run data; - data.run_name = reports[0].run_name; - data.run_type = BenchmarkReporter::Run::RT_Aggregate; - data.threads = reports[0].threads; - data.repetitions = reports[0].repetitions; - data.repetition_index = Run::no_repetition_index; - data.aggregate_name = Stat.name_; - data.report_label = report_label; - - // It is incorrect to say that an aggregate is computed over - // run's iterations, because those iterations already got averaged. - // Similarly, if there are N repetitions with 1 iterations each, - // an aggregate will be computed over N measurements, not 1. - // Thus it is best to simply use the count of separate reports. - data.iterations = reports.size(); - - data.real_accumulated_time = Stat.compute_(real_accumulated_time_stat); - data.cpu_accumulated_time = Stat.compute_(cpu_accumulated_time_stat); - - // We will divide these times by data.iterations when reporting, but the - // data.iterations is not nessesairly the scale of these measurements, - // because in each repetition, these timers are sum over all the iterations. - // And if we want to say that the stats are over N repetitions and not - // M iterations, we need to multiply these by (N/M). - data.real_accumulated_time *= iteration_rescale_factor; - data.cpu_accumulated_time *= iteration_rescale_factor; - - data.time_unit = reports[0].time_unit; - - // user counters - for (auto const& kv : counter_stats) { - // Do *NOT* rescale the custom counters. They are already properly scaled. - const auto uc_stat = Stat.compute_(kv.second.s); - auto c = Counter(uc_stat, counter_stats[kv.first].c.flags, - counter_stats[kv.first].c.oneK); - data.counters[kv.first] = c; - } - - results.push_back(data); - } - - return results; -} - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/statistics.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/statistics.h deleted file mode 100644 index 7eccc85536a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/statistics.h +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 Ismael Jimenez Martinez. All rights reserved. -// Copyright 2017 Roman Lebedev. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef STATISTICS_H_ -#define STATISTICS_H_ - -#include - -#include "benchmark/benchmark.h" - -namespace benchmark { - -// Return a vector containing the mean, median and standard devation information -// (and any user-specified info) for the specified list of reports. If 'reports' -// contains less than two non-errored runs an empty vector is returned -std::vector ComputeStats( - const std::vector& reports); - -double StatisticsMean(const std::vector& v); -double StatisticsMedian(const std::vector& v); -double StatisticsStdDev(const std::vector& v); - -} // end namespace benchmark - -#endif // STATISTICS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/string_util.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/string_util.cc deleted file mode 100644 index 39b01a1719a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/string_util.cc +++ /dev/null @@ -1,252 +0,0 @@ -#include "string_util.h" - -#include -#include -#include -#include -#include -#include - -#include "arraysize.h" - -namespace benchmark { -namespace { - -// kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta. -const char kBigSIUnits[] = "kMGTPEZY"; -// Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi. -const char kBigIECUnits[] = "KMGTPEZY"; -// milli, micro, nano, pico, femto, atto, zepto, yocto. -const char kSmallSIUnits[] = "munpfazy"; - -// We require that all three arrays have the same size. -static_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits), - "SI and IEC unit arrays must be the same size"); -static_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits), - "Small SI and Big SI unit arrays must be the same size"); - -static const int64_t kUnitsSize = arraysize(kBigSIUnits); - -void ToExponentAndMantissa(double val, double thresh, int precision, - double one_k, std::string* mantissa, - int64_t* exponent) { - std::stringstream mantissa_stream; - - if (val < 0) { - mantissa_stream << "-"; - val = -val; - } - - // Adjust threshold so that it never excludes things which can't be rendered - // in 'precision' digits. - const double adjusted_threshold = - std::max(thresh, 1.0 / std::pow(10.0, precision)); - const double big_threshold = adjusted_threshold * one_k; - const double small_threshold = adjusted_threshold; - // Values in ]simple_threshold,small_threshold[ will be printed as-is - const double simple_threshold = 0.01; - - if (val > big_threshold) { - // Positive powers - double scaled = val; - for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) { - scaled /= one_k; - if (scaled <= big_threshold) { - mantissa_stream << scaled; - *exponent = i + 1; - *mantissa = mantissa_stream.str(); - return; - } - } - mantissa_stream << val; - *exponent = 0; - } else if (val < small_threshold) { - // Negative powers - if (val < simple_threshold) { - double scaled = val; - for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) { - scaled *= one_k; - if (scaled >= small_threshold) { - mantissa_stream << scaled; - *exponent = -static_cast(i + 1); - *mantissa = mantissa_stream.str(); - return; - } - } - } - mantissa_stream << val; - *exponent = 0; - } else { - mantissa_stream << val; - *exponent = 0; - } - *mantissa = mantissa_stream.str(); -} - -std::string ExponentToPrefix(int64_t exponent, bool iec) { - if (exponent == 0) return ""; - - const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1); - if (index >= kUnitsSize) return ""; - - const char* array = - (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits); - if (iec) - return array[index] + std::string("i"); - else - return std::string(1, array[index]); -} - -std::string ToBinaryStringFullySpecified(double value, double threshold, - int precision, double one_k = 1024.0) { - std::string mantissa; - int64_t exponent; - ToExponentAndMantissa(value, threshold, precision, one_k, &mantissa, - &exponent); - return mantissa + ExponentToPrefix(exponent, false); -} - -} // end namespace - -void AppendHumanReadable(int n, std::string* str) { - std::stringstream ss; - // Round down to the nearest SI prefix. - ss << ToBinaryStringFullySpecified(n, 1.0, 0); - *str += ss.str(); -} - -std::string HumanReadableNumber(double n, double one_k) { - // 1.1 means that figures up to 1.1k should be shown with the next unit down; - // this softens edge effects. - // 1 means that we should show one decimal place of precision. - return ToBinaryStringFullySpecified(n, 1.1, 1, one_k); -} - -std::string StrFormatImp(const char* msg, va_list args) { - // we might need a second shot at this, so pre-emptivly make a copy - va_list args_cp; - va_copy(args_cp, args); - - // TODO(ericwf): use std::array for first attempt to avoid one memory - // allocation guess what the size might be - std::array local_buff; - std::size_t size = local_buff.size(); - // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation - // in the android-ndk - auto ret = vsnprintf(local_buff.data(), size, msg, args_cp); - - va_end(args_cp); - - // handle empty expansion - if (ret == 0) return std::string{}; - if (static_cast(ret) < size) - return std::string(local_buff.data()); - - // we did not provide a long enough buffer on our first attempt. - // add 1 to size to account for null-byte in size cast to prevent overflow - size = static_cast(ret) + 1; - auto buff_ptr = std::unique_ptr(new char[size]); - // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation - // in the android-ndk - ret = vsnprintf(buff_ptr.get(), size, msg, args); - return std::string(buff_ptr.get()); -} - -std::string StrFormat(const char* format, ...) { - va_list args; - va_start(args, format); - std::string tmp = StrFormatImp(format, args); - va_end(args); - return tmp; -} - -#ifdef BENCHMARK_STL_ANDROID_GNUSTL -/* - * GNU STL in Android NDK lacks support for some C++11 functions, including - * stoul, stoi, stod. We reimplement them here using C functions strtoul, - * strtol, strtod. Note that reimplemented functions are in benchmark:: - * namespace, not std:: namespace. - */ -unsigned long stoul(const std::string& str, size_t* pos, int base) { - /* Record previous errno */ - const int oldErrno = errno; - errno = 0; - - const char* strStart = str.c_str(); - char* strEnd = const_cast(strStart); - const unsigned long result = strtoul(strStart, &strEnd, base); - - const int strtoulErrno = errno; - /* Restore previous errno */ - errno = oldErrno; - - /* Check for errors and return */ - if (strtoulErrno == ERANGE) { - throw std::out_of_range( - "stoul failed: " + str + " is outside of range of unsigned long"); - } else if (strEnd == strStart || strtoulErrno != 0) { - throw std::invalid_argument( - "stoul failed: " + str + " is not an integer"); - } - if (pos != nullptr) { - *pos = static_cast(strEnd - strStart); - } - return result; -} - -int stoi(const std::string& str, size_t* pos, int base) { - /* Record previous errno */ - const int oldErrno = errno; - errno = 0; - - const char* strStart = str.c_str(); - char* strEnd = const_cast(strStart); - const long result = strtol(strStart, &strEnd, base); - - const int strtolErrno = errno; - /* Restore previous errno */ - errno = oldErrno; - - /* Check for errors and return */ - if (strtolErrno == ERANGE || long(int(result)) != result) { - throw std::out_of_range( - "stoul failed: " + str + " is outside of range of int"); - } else if (strEnd == strStart || strtolErrno != 0) { - throw std::invalid_argument( - "stoul failed: " + str + " is not an integer"); - } - if (pos != nullptr) { - *pos = static_cast(strEnd - strStart); - } - return int(result); -} - -double stod(const std::string& str, size_t* pos) { - /* Record previous errno */ - const int oldErrno = errno; - errno = 0; - - const char* strStart = str.c_str(); - char* strEnd = const_cast(strStart); - const double result = strtod(strStart, &strEnd); - - /* Restore previous errno */ - const int strtodErrno = errno; - errno = oldErrno; - - /* Check for errors and return */ - if (strtodErrno == ERANGE) { - throw std::out_of_range( - "stoul failed: " + str + " is outside of range of int"); - } else if (strEnd == strStart || strtodErrno != 0) { - throw std::invalid_argument( - "stoul failed: " + str + " is not an integer"); - } - if (pos != nullptr) { - *pos = static_cast(strEnd - strStart); - } - return result; -} -#endif - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/string_util.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/string_util.h deleted file mode 100644 index 09d7b4bd2a9..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/string_util.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef BENCHMARK_STRING_UTIL_H_ -#define BENCHMARK_STRING_UTIL_H_ - -#include -#include -#include -#include "internal_macros.h" - -namespace benchmark { - -void AppendHumanReadable(int n, std::string* str); - -std::string HumanReadableNumber(double n, double one_k = 1024.0); - -#if defined(__MINGW32__) -__attribute__((format(__MINGW_PRINTF_FORMAT, 1, 2))) -#elif defined(__GNUC__) -__attribute__((format(printf, 1, 2))) -#endif -std::string -StrFormat(const char* format, ...); - -inline std::ostream& StrCatImp(std::ostream& out) BENCHMARK_NOEXCEPT { - return out; -} - -template -inline std::ostream& StrCatImp(std::ostream& out, First&& f, Rest&&... rest) { - out << std::forward(f); - return StrCatImp(out, std::forward(rest)...); -} - -template -inline std::string StrCat(Args&&... args) { - std::ostringstream ss; - StrCatImp(ss, std::forward(args)...); - return ss.str(); -} - -#ifdef BENCHMARK_STL_ANDROID_GNUSTL -/* - * GNU STL in Android NDK lacks support for some C++11 functions, including - * stoul, stoi, stod. We reimplement them here using C functions strtoul, - * strtol, strtod. Note that reimplemented functions are in benchmark:: - * namespace, not std:: namespace. - */ -unsigned long stoul(const std::string& str, size_t* pos = nullptr, - int base = 10); -int stoi(const std::string& str, size_t* pos = nullptr, int base = 10); -double stod(const std::string& str, size_t* pos = nullptr); -#else -using std::stoul; -using std::stoi; -using std::stod; -#endif - -} // end namespace benchmark - -#endif // BENCHMARK_STRING_UTIL_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/sysinfo.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/sysinfo.cc deleted file mode 100644 index 28126470bad..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/sysinfo.cc +++ /dev/null @@ -1,699 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "internal_macros.h" - -#ifdef BENCHMARK_OS_WINDOWS -#include -#undef StrCat // Don't let StrCat in string_util.h be renamed to lstrcatA -#include -#include -#include -#else -#include -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD -#include -#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX || \ - defined BENCHMARK_OS_NETBSD || defined BENCHMARK_OS_OPENBSD -#define BENCHMARK_HAS_SYSCTL -#include -#endif -#endif -#if defined(BENCHMARK_OS_SOLARIS) -#include -#endif -#if defined(BENCHMARK_OS_QNX) -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "cycleclock.h" -#include "internal_macros.h" -#include "log.h" -#include "sleep.h" -#include "string_util.h" - -namespace benchmark { -namespace { - -void PrintImp(std::ostream& out) { out << std::endl; } - -template -void PrintImp(std::ostream& out, First&& f, Rest&&... rest) { - out << std::forward(f); - PrintImp(out, std::forward(rest)...); -} - -template -BENCHMARK_NORETURN void PrintErrorAndDie(Args&&... args) { - PrintImp(std::cerr, std::forward(args)...); - std::exit(EXIT_FAILURE); -} - -#ifdef BENCHMARK_HAS_SYSCTL - -/// ValueUnion - A type used to correctly alias the byte-for-byte output of -/// `sysctl` with the result type it's to be interpreted as. -struct ValueUnion { - union DataT { - uint32_t uint32_value; - uint64_t uint64_value; - // For correct aliasing of union members from bytes. - char bytes[8]; - }; - using DataPtr = std::unique_ptr; - - // The size of the data union member + its trailing array size. - size_t Size; - DataPtr Buff; - - public: - ValueUnion() : Size(0), Buff(nullptr, &std::free) {} - - explicit ValueUnion(size_t BuffSize) - : Size(sizeof(DataT) + BuffSize), - Buff(::new (std::malloc(Size)) DataT(), &std::free) {} - - ValueUnion(ValueUnion&& other) = default; - - explicit operator bool() const { return bool(Buff); } - - char* data() const { return Buff->bytes; } - - std::string GetAsString() const { return std::string(data()); } - - int64_t GetAsInteger() const { - if (Size == sizeof(Buff->uint32_value)) - return static_cast(Buff->uint32_value); - else if (Size == sizeof(Buff->uint64_value)) - return static_cast(Buff->uint64_value); - BENCHMARK_UNREACHABLE(); - } - - uint64_t GetAsUnsigned() const { - if (Size == sizeof(Buff->uint32_value)) - return Buff->uint32_value; - else if (Size == sizeof(Buff->uint64_value)) - return Buff->uint64_value; - BENCHMARK_UNREACHABLE(); - } - - template - std::array GetAsArray() { - const int ArrSize = sizeof(T) * N; - CHECK_LE(ArrSize, Size); - std::array Arr; - std::memcpy(Arr.data(), data(), ArrSize); - return Arr; - } -}; - -ValueUnion GetSysctlImp(std::string const& Name) { -#if defined BENCHMARK_OS_OPENBSD - int mib[2]; - - mib[0] = CTL_HW; - if ((Name == "hw.ncpu") || (Name == "hw.cpuspeed")){ - ValueUnion buff(sizeof(int)); - - if (Name == "hw.ncpu") { - mib[1] = HW_NCPU; - } else { - mib[1] = HW_CPUSPEED; - } - - if (sysctl(mib, 2, buff.data(), &buff.Size, nullptr, 0) == -1) { - return ValueUnion(); - } - return buff; - } - return ValueUnion(); -#else - size_t CurBuffSize = 0; - if (sysctlbyname(Name.c_str(), nullptr, &CurBuffSize, nullptr, 0) == -1) - return ValueUnion(); - - ValueUnion buff(CurBuffSize); - if (sysctlbyname(Name.c_str(), buff.data(), &buff.Size, nullptr, 0) == 0) - return buff; - return ValueUnion(); -#endif -} - -BENCHMARK_MAYBE_UNUSED -bool GetSysctl(std::string const& Name, std::string* Out) { - Out->clear(); - auto Buff = GetSysctlImp(Name); - if (!Buff) return false; - Out->assign(Buff.data()); - return true; -} - -template ::value>::type> -bool GetSysctl(std::string const& Name, Tp* Out) { - *Out = 0; - auto Buff = GetSysctlImp(Name); - if (!Buff) return false; - *Out = static_cast(Buff.GetAsUnsigned()); - return true; -} - -template -bool GetSysctl(std::string const& Name, std::array* Out) { - auto Buff = GetSysctlImp(Name); - if (!Buff) return false; - *Out = Buff.GetAsArray(); - return true; -} -#endif - -template -bool ReadFromFile(std::string const& fname, ArgT* arg) { - *arg = ArgT(); - std::ifstream f(fname.c_str()); - if (!f.is_open()) return false; - f >> *arg; - return f.good(); -} - -bool CpuScalingEnabled(int num_cpus) { - // We don't have a valid CPU count, so don't even bother. - if (num_cpus <= 0) return false; -#ifdef BENCHMARK_OS_QNX - return false; -#endif -#ifndef BENCHMARK_OS_WINDOWS - // On Linux, the CPUfreq subsystem exposes CPU information as files on the - // local file system. If reading the exported files fails, then we may not be - // running on Linux, so we silently ignore all the read errors. - std::string res; - for (int cpu = 0; cpu < num_cpus; ++cpu) { - std::string governor_file = - StrCat("/sys/devices/system/cpu/cpu", cpu, "/cpufreq/scaling_governor"); - if (ReadFromFile(governor_file, &res) && res != "performance") return true; - } -#endif - return false; -} - -int CountSetBitsInCPUMap(std::string Val) { - auto CountBits = [](std::string Part) { - using CPUMask = std::bitset; - Part = "0x" + Part; - CPUMask Mask(benchmark::stoul(Part, nullptr, 16)); - return static_cast(Mask.count()); - }; - size_t Pos; - int total = 0; - while ((Pos = Val.find(',')) != std::string::npos) { - total += CountBits(Val.substr(0, Pos)); - Val = Val.substr(Pos + 1); - } - if (!Val.empty()) { - total += CountBits(Val); - } - return total; -} - -BENCHMARK_MAYBE_UNUSED -std::vector GetCacheSizesFromKVFS() { - std::vector res; - std::string dir = "/sys/devices/system/cpu/cpu0/cache/"; - int Idx = 0; - while (true) { - CPUInfo::CacheInfo info; - std::string FPath = StrCat(dir, "index", Idx++, "/"); - std::ifstream f(StrCat(FPath, "size").c_str()); - if (!f.is_open()) break; - std::string suffix; - f >> info.size; - if (f.fail()) - PrintErrorAndDie("Failed while reading file '", FPath, "size'"); - if (f.good()) { - f >> suffix; - if (f.bad()) - PrintErrorAndDie( - "Invalid cache size format: failed to read size suffix"); - else if (f && suffix != "K") - PrintErrorAndDie("Invalid cache size format: Expected bytes ", suffix); - else if (suffix == "K") - info.size *= 1000; - } - if (!ReadFromFile(StrCat(FPath, "type"), &info.type)) - PrintErrorAndDie("Failed to read from file ", FPath, "type"); - if (!ReadFromFile(StrCat(FPath, "level"), &info.level)) - PrintErrorAndDie("Failed to read from file ", FPath, "level"); - std::string map_str; - if (!ReadFromFile(StrCat(FPath, "shared_cpu_map"), &map_str)) - PrintErrorAndDie("Failed to read from file ", FPath, "shared_cpu_map"); - info.num_sharing = CountSetBitsInCPUMap(map_str); - res.push_back(info); - } - - return res; -} - -#ifdef BENCHMARK_OS_MACOSX -std::vector GetCacheSizesMacOSX() { - std::vector res; - std::array CacheCounts{{0, 0, 0, 0}}; - GetSysctl("hw.cacheconfig", &CacheCounts); - - struct { - std::string name; - std::string type; - int level; - uint64_t num_sharing; - } Cases[] = {{"hw.l1dcachesize", "Data", 1, CacheCounts[1]}, - {"hw.l1icachesize", "Instruction", 1, CacheCounts[1]}, - {"hw.l2cachesize", "Unified", 2, CacheCounts[2]}, - {"hw.l3cachesize", "Unified", 3, CacheCounts[3]}}; - for (auto& C : Cases) { - int val; - if (!GetSysctl(C.name, &val)) continue; - CPUInfo::CacheInfo info; - info.type = C.type; - info.level = C.level; - info.size = val; - info.num_sharing = static_cast(C.num_sharing); - res.push_back(std::move(info)); - } - return res; -} -#elif defined(BENCHMARK_OS_WINDOWS) -std::vector GetCacheSizesWindows() { - std::vector res; - DWORD buffer_size = 0; - using PInfo = SYSTEM_LOGICAL_PROCESSOR_INFORMATION; - using CInfo = CACHE_DESCRIPTOR; - - using UPtr = std::unique_ptr; - GetLogicalProcessorInformation(nullptr, &buffer_size); - UPtr buff((PInfo*)malloc(buffer_size), &std::free); - if (!GetLogicalProcessorInformation(buff.get(), &buffer_size)) - PrintErrorAndDie("Failed during call to GetLogicalProcessorInformation: ", - GetLastError()); - - PInfo* it = buff.get(); - PInfo* end = buff.get() + (buffer_size / sizeof(PInfo)); - - for (; it != end; ++it) { - if (it->Relationship != RelationCache) continue; - using BitSet = std::bitset; - BitSet B(it->ProcessorMask); - // To prevent duplicates, only consider caches where CPU 0 is specified - if (!B.test(0)) continue; - CInfo* Cache = &it->Cache; - CPUInfo::CacheInfo C; - C.num_sharing = static_cast(B.count()); - C.level = Cache->Level; - C.size = Cache->Size; - switch (Cache->Type) { - case CacheUnified: - C.type = "Unified"; - break; - case CacheInstruction: - C.type = "Instruction"; - break; - case CacheData: - C.type = "Data"; - break; - case CacheTrace: - C.type = "Trace"; - break; - default: - C.type = "Unknown"; - break; - } - res.push_back(C); - } - return res; -} -#elif BENCHMARK_OS_QNX -std::vector GetCacheSizesQNX() { - std::vector res; - struct cacheattr_entry *cache = SYSPAGE_ENTRY(cacheattr); - uint32_t const elsize = SYSPAGE_ELEMENT_SIZE(cacheattr); - int num = SYSPAGE_ENTRY_SIZE(cacheattr) / elsize ; - for(int i = 0; i < num; ++i ) { - CPUInfo::CacheInfo info; - switch (cache->flags){ - case CACHE_FLAG_INSTR : - info.type = "Instruction"; - info.level = 1; - break; - case CACHE_FLAG_DATA : - info.type = "Data"; - info.level = 1; - break; - case CACHE_FLAG_UNIFIED : - info.type = "Unified"; - info.level = 2; - case CACHE_FLAG_SHARED : - info.type = "Shared"; - info.level = 3; - default : - continue; - break; - } - info.size = cache->line_size * cache->num_lines; - info.num_sharing = 0; - res.push_back(std::move(info)); - cache = SYSPAGE_ARRAY_ADJ_OFFSET(cacheattr, cache, elsize); - } - return res; -} -#endif - -std::vector GetCacheSizes() { -#ifdef BENCHMARK_OS_MACOSX - return GetCacheSizesMacOSX(); -#elif defined(BENCHMARK_OS_WINDOWS) - return GetCacheSizesWindows(); -#elif defined(BENCHMARK_OS_QNX) - return GetCacheSizesQNX(); -#else - return GetCacheSizesFromKVFS(); -#endif -} - -std::string GetSystemName() { -#if defined(BENCHMARK_OS_WINDOWS) - std::string str; - const unsigned COUNT = MAX_COMPUTERNAME_LENGTH+1; - TCHAR hostname[COUNT] = {'\0'}; - DWORD DWCOUNT = COUNT; - if (!GetComputerName(hostname, &DWCOUNT)) - return std::string(""); -#ifndef UNICODE - str = std::string(hostname, DWCOUNT); -#else - //Using wstring_convert, Is deprecated in C++17 - using convert_type = std::codecvt_utf8; - std::wstring_convert converter; - std::wstring wStr(hostname, DWCOUNT); - str = converter.to_bytes(wStr); -#endif - return str; -#else // defined(BENCHMARK_OS_WINDOWS) -#ifdef BENCHMARK_HAS_SYSCTL // BSD/Mac Doesnt have HOST_NAME_MAX defined -#define HOST_NAME_MAX 64 -#elif defined(BENCHMARK_OS_QNX) -#define HOST_NAME_MAX 154 -#endif - char hostname[HOST_NAME_MAX]; - int retVal = gethostname(hostname, HOST_NAME_MAX); - if (retVal != 0) return std::string(""); - return std::string(hostname); -#endif // Catch-all POSIX block. -} - -int GetNumCPUs() { -#ifdef BENCHMARK_HAS_SYSCTL - int NumCPU = -1; - if (GetSysctl("hw.ncpu", &NumCPU)) return NumCPU; - fprintf(stderr, "Err: %s\n", strerror(errno)); - std::exit(EXIT_FAILURE); -#elif defined(BENCHMARK_OS_WINDOWS) - SYSTEM_INFO sysinfo; - // Use memset as opposed to = {} to avoid GCC missing initializer false - // positives. - std::memset(&sysinfo, 0, sizeof(SYSTEM_INFO)); - GetSystemInfo(&sysinfo); - return sysinfo.dwNumberOfProcessors; // number of logical - // processors in the current - // group -#elif defined(BENCHMARK_OS_SOLARIS) - // Returns -1 in case of a failure. - int NumCPU = sysconf(_SC_NPROCESSORS_ONLN); - if (NumCPU < 0) { - fprintf(stderr, - "sysconf(_SC_NPROCESSORS_ONLN) failed with error: %s\n", - strerror(errno)); - } - return NumCPU; -#elif defined(BENCHMARK_OS_QNX) - return static_cast(_syspage_ptr->num_cpu); -#else - int NumCPUs = 0; - int MaxID = -1; - std::ifstream f("/proc/cpuinfo"); - if (!f.is_open()) { - std::cerr << "failed to open /proc/cpuinfo\n"; - return -1; - } - const std::string Key = "processor"; - std::string ln; - while (std::getline(f, ln)) { - if (ln.empty()) continue; - size_t SplitIdx = ln.find(':'); - std::string value; -#if defined(__s390__) - // s390 has another format in /proc/cpuinfo - // it needs to be parsed differently - if (SplitIdx != std::string::npos) value = ln.substr(Key.size()+1,SplitIdx-Key.size()-1); -#else - if (SplitIdx != std::string::npos) value = ln.substr(SplitIdx + 1); -#endif - if (ln.size() >= Key.size() && ln.compare(0, Key.size(), Key) == 0) { - NumCPUs++; - if (!value.empty()) { - int CurID = benchmark::stoi(value); - MaxID = std::max(CurID, MaxID); - } - } - } - if (f.bad()) { - std::cerr << "Failure reading /proc/cpuinfo\n"; - return -1; - } - if (!f.eof()) { - std::cerr << "Failed to read to end of /proc/cpuinfo\n"; - return -1; - } - f.close(); - - if ((MaxID + 1) != NumCPUs) { - fprintf(stderr, - "CPU ID assignments in /proc/cpuinfo seem messed up." - " This is usually caused by a bad BIOS.\n"); - } - return NumCPUs; -#endif - BENCHMARK_UNREACHABLE(); -} - -double GetCPUCyclesPerSecond() { -#if defined BENCHMARK_OS_LINUX || defined BENCHMARK_OS_CYGWIN - long freq; - - // If the kernel is exporting the tsc frequency use that. There are issues - // where cpuinfo_max_freq cannot be relied on because the BIOS may be - // exporintg an invalid p-state (on x86) or p-states may be used to put the - // processor in a new mode (turbo mode). Essentially, those frequencies - // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as - // well. - if (ReadFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq) - // If CPU scaling is in effect, we want to use the *maximum* frequency, - // not whatever CPU speed some random processor happens to be using now. - || ReadFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", - &freq)) { - // The value is in kHz (as the file name suggests). For example, on a - // 2GHz warpstation, the file contains the value "2000000". - return freq * 1000.0; - } - - const double error_value = -1; - double bogo_clock = error_value; - - std::ifstream f("/proc/cpuinfo"); - if (!f.is_open()) { - std::cerr << "failed to open /proc/cpuinfo\n"; - return error_value; - } - - auto startsWithKey = [](std::string const& Value, std::string const& Key) { - if (Key.size() > Value.size()) return false; - auto Cmp = [&](char X, char Y) { - return std::tolower(X) == std::tolower(Y); - }; - return std::equal(Key.begin(), Key.end(), Value.begin(), Cmp); - }; - - std::string ln; - while (std::getline(f, ln)) { - if (ln.empty()) continue; - size_t SplitIdx = ln.find(':'); - std::string value; - if (SplitIdx != std::string::npos) value = ln.substr(SplitIdx + 1); - // When parsing the "cpu MHz" and "bogomips" (fallback) entries, we only - // accept positive values. Some environments (virtual machines) report zero, - // which would cause infinite looping in WallTime_Init. - if (startsWithKey(ln, "cpu MHz")) { - if (!value.empty()) { - double cycles_per_second = benchmark::stod(value) * 1000000.0; - if (cycles_per_second > 0) return cycles_per_second; - } - } else if (startsWithKey(ln, "bogomips")) { - if (!value.empty()) { - bogo_clock = benchmark::stod(value) * 1000000.0; - if (bogo_clock < 0.0) bogo_clock = error_value; - } - } - } - if (f.bad()) { - std::cerr << "Failure reading /proc/cpuinfo\n"; - return error_value; - } - if (!f.eof()) { - std::cerr << "Failed to read to end of /proc/cpuinfo\n"; - return error_value; - } - f.close(); - // If we found the bogomips clock, but nothing better, we'll use it (but - // we're not happy about it); otherwise, fallback to the rough estimation - // below. - if (bogo_clock >= 0.0) return bogo_clock; - -#elif defined BENCHMARK_HAS_SYSCTL - constexpr auto* FreqStr = -#if defined(BENCHMARK_OS_FREEBSD) || defined(BENCHMARK_OS_NETBSD) - "machdep.tsc_freq"; -#elif defined BENCHMARK_OS_OPENBSD - "hw.cpuspeed"; -#else - "hw.cpufrequency"; -#endif - unsigned long long hz = 0; -#if defined BENCHMARK_OS_OPENBSD - if (GetSysctl(FreqStr, &hz)) return hz * 1000000; -#else - if (GetSysctl(FreqStr, &hz)) return hz; -#endif - fprintf(stderr, "Unable to determine clock rate from sysctl: %s: %s\n", - FreqStr, strerror(errno)); - -#elif defined BENCHMARK_OS_WINDOWS - // In NT, read MHz from the registry. If we fail to do so or we're in win9x - // then make a crude estimate. - DWORD data, data_size = sizeof(data); - if (IsWindowsXPOrGreater() && - SUCCEEDED( - SHGetValueA(HKEY_LOCAL_MACHINE, - "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", - "~MHz", nullptr, &data, &data_size))) - return static_cast((int64_t)data * - (int64_t)(1000 * 1000)); // was mhz -#elif defined (BENCHMARK_OS_SOLARIS) - kstat_ctl_t *kc = kstat_open(); - if (!kc) { - std::cerr << "failed to open /dev/kstat\n"; - return -1; - } - kstat_t *ksp = kstat_lookup(kc, (char*)"cpu_info", -1, (char*)"cpu_info0"); - if (!ksp) { - std::cerr << "failed to lookup in /dev/kstat\n"; - return -1; - } - if (kstat_read(kc, ksp, NULL) < 0) { - std::cerr << "failed to read from /dev/kstat\n"; - return -1; - } - kstat_named_t *knp = - (kstat_named_t*)kstat_data_lookup(ksp, (char*)"current_clock_Hz"); - if (!knp) { - std::cerr << "failed to lookup data in /dev/kstat\n"; - return -1; - } - if (knp->data_type != KSTAT_DATA_UINT64) { - std::cerr << "current_clock_Hz is of unexpected data type: " - << knp->data_type << "\n"; - return -1; - } - double clock_hz = knp->value.ui64; - kstat_close(kc); - return clock_hz; -#elif defined (BENCHMARK_OS_QNX) - return static_cast((int64_t)(SYSPAGE_ENTRY(cpuinfo)->speed) * - (int64_t)(1000 * 1000)); -#endif - // If we've fallen through, attempt to roughly estimate the CPU clock rate. - const int estimate_time_ms = 1000; - const auto start_ticks = cycleclock::Now(); - SleepForMilliseconds(estimate_time_ms); - return static_cast(cycleclock::Now() - start_ticks); -} - -std::vector GetLoadAvg() { -#if (defined BENCHMARK_OS_FREEBSD || defined(BENCHMARK_OS_LINUX) || \ - defined BENCHMARK_OS_MACOSX || defined BENCHMARK_OS_NETBSD || \ - defined BENCHMARK_OS_OPENBSD) && !defined(__ANDROID__) - constexpr int kMaxSamples = 3; - std::vector res(kMaxSamples, 0.0); - const int nelem = getloadavg(res.data(), kMaxSamples); - if (nelem < 1) { - res.clear(); - } else { - res.resize(nelem); - } - return res; -#else - return {}; -#endif -} - -} // end namespace - -const CPUInfo& CPUInfo::Get() { - static const CPUInfo* info = new CPUInfo(); - return *info; -} - -CPUInfo::CPUInfo() - : num_cpus(GetNumCPUs()), - cycles_per_second(GetCPUCyclesPerSecond()), - caches(GetCacheSizes()), - scaling_enabled(CpuScalingEnabled(num_cpus)), - load_avg(GetLoadAvg()) {} - - -const SystemInfo& SystemInfo::Get() { - static const SystemInfo* info = new SystemInfo(); - return *info; -} - -SystemInfo::SystemInfo() : name(GetSystemName()) {} -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/thread_manager.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/thread_manager.h deleted file mode 100644 index 1720281f0a1..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/thread_manager.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef BENCHMARK_THREAD_MANAGER_H -#define BENCHMARK_THREAD_MANAGER_H - -#include - -#include "benchmark/benchmark.h" -#include "mutex.h" - -namespace benchmark { -namespace internal { - -class ThreadManager { - public: - ThreadManager(int num_threads) - : alive_threads_(num_threads), start_stop_barrier_(num_threads) {} - - Mutex& GetBenchmarkMutex() const RETURN_CAPABILITY(benchmark_mutex_) { - return benchmark_mutex_; - } - - bool StartStopBarrier() EXCLUDES(end_cond_mutex_) { - return start_stop_barrier_.wait(); - } - - void NotifyThreadComplete() EXCLUDES(end_cond_mutex_) { - start_stop_barrier_.removeThread(); - if (--alive_threads_ == 0) { - MutexLock lock(end_cond_mutex_); - end_condition_.notify_all(); - } - } - - void WaitForAllThreads() EXCLUDES(end_cond_mutex_) { - MutexLock lock(end_cond_mutex_); - end_condition_.wait(lock.native_handle(), - [this]() { return alive_threads_ == 0; }); - } - - public: - struct Result { - IterationCount iterations = 0; - double real_time_used = 0; - double cpu_time_used = 0; - double manual_time_used = 0; - int64_t complexity_n = 0; - std::string report_label_; - std::string error_message_; - bool has_error_ = false; - UserCounters counters; - }; - GUARDED_BY(GetBenchmarkMutex()) Result results; - - private: - mutable Mutex benchmark_mutex_; - std::atomic alive_threads_; - Barrier start_stop_barrier_; - Mutex end_cond_mutex_; - Condition end_condition_; -}; - -} // namespace internal -} // namespace benchmark - -#endif // BENCHMARK_THREAD_MANAGER_H diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/thread_timer.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/thread_timer.h deleted file mode 100644 index fbd298d3bd4..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/thread_timer.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef BENCHMARK_THREAD_TIMER_H -#define BENCHMARK_THREAD_TIMER_H - -#include "check.h" -#include "timers.h" - -namespace benchmark { -namespace internal { - -class ThreadTimer { - explicit ThreadTimer(bool measure_process_cpu_time_) - : measure_process_cpu_time(measure_process_cpu_time_) {} - - public: - static ThreadTimer Create() { - return ThreadTimer(/*measure_process_cpu_time_=*/false); - } - static ThreadTimer CreateProcessCpuTime() { - return ThreadTimer(/*measure_process_cpu_time_=*/true); - } - - // Called by each thread - void StartTimer() { - running_ = true; - start_real_time_ = ChronoClockNow(); - start_cpu_time_ = ReadCpuTimerOfChoice(); - } - - // Called by each thread - void StopTimer() { - CHECK(running_); - running_ = false; - real_time_used_ += ChronoClockNow() - start_real_time_; - // Floating point error can result in the subtraction producing a negative - // time. Guard against that. - cpu_time_used_ += - std::max(ReadCpuTimerOfChoice() - start_cpu_time_, 0); - } - - // Called by each thread - void SetIterationTime(double seconds) { manual_time_used_ += seconds; } - - bool running() const { return running_; } - - // REQUIRES: timer is not running - double real_time_used() { - CHECK(!running_); - return real_time_used_; - } - - // REQUIRES: timer is not running - double cpu_time_used() { - CHECK(!running_); - return cpu_time_used_; - } - - // REQUIRES: timer is not running - double manual_time_used() { - CHECK(!running_); - return manual_time_used_; - } - - private: - double ReadCpuTimerOfChoice() const { - if (measure_process_cpu_time) return ProcessCPUUsage(); - return ThreadCPUUsage(); - } - - // should the thread, or the process, time be measured? - const bool measure_process_cpu_time; - - bool running_ = false; // Is the timer running - double start_real_time_ = 0; // If running_ - double start_cpu_time_ = 0; // If running_ - - // Accumulated time so far (does not contain current slice if running_) - double real_time_used_ = 0; - double cpu_time_used_ = 0; - // Manually set iteration time. User sets this with SetIterationTime(seconds). - double manual_time_used_ = 0; -}; - -} // namespace internal -} // namespace benchmark - -#endif // BENCHMARK_THREAD_TIMER_H diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/timers.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/timers.cc deleted file mode 100644 index 7613ff92c6e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/timers.cc +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "timers.h" -#include "internal_macros.h" - -#ifdef BENCHMARK_OS_WINDOWS -#include -#undef StrCat // Don't let StrCat in string_util.h be renamed to lstrcatA -#include -#include -#else -#include -#ifndef BENCHMARK_OS_FUCHSIA -#include -#endif -#include -#include // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD -#include -#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX -#include -#endif -#if defined(BENCHMARK_OS_MACOSX) -#include -#include -#include -#endif -#endif - -#ifdef BENCHMARK_OS_EMSCRIPTEN -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "check.h" -#include "log.h" -#include "sleep.h" -#include "string_util.h" - -namespace benchmark { - -// Suppress unused warnings on helper functions. -#if defined(__GNUC__) -#pragma GCC diagnostic ignored "-Wunused-function" -#endif - -namespace { -#if defined(BENCHMARK_OS_WINDOWS) -double MakeTime(FILETIME const& kernel_time, FILETIME const& user_time) { - ULARGE_INTEGER kernel; - ULARGE_INTEGER user; - kernel.HighPart = kernel_time.dwHighDateTime; - kernel.LowPart = kernel_time.dwLowDateTime; - user.HighPart = user_time.dwHighDateTime; - user.LowPart = user_time.dwLowDateTime; - return (static_cast(kernel.QuadPart) + - static_cast(user.QuadPart)) * - 1e-7; -} -#elif !defined(BENCHMARK_OS_FUCHSIA) -double MakeTime(struct rusage const& ru) { - return (static_cast(ru.ru_utime.tv_sec) + - static_cast(ru.ru_utime.tv_usec) * 1e-6 + - static_cast(ru.ru_stime.tv_sec) + - static_cast(ru.ru_stime.tv_usec) * 1e-6); -} -#endif -#if defined(BENCHMARK_OS_MACOSX) -double MakeTime(thread_basic_info_data_t const& info) { - return (static_cast(info.user_time.seconds) + - static_cast(info.user_time.microseconds) * 1e-6 + - static_cast(info.system_time.seconds) + - static_cast(info.system_time.microseconds) * 1e-6); -} -#endif -#if defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_THREAD_CPUTIME_ID) -double MakeTime(struct timespec const& ts) { - return ts.tv_sec + (static_cast(ts.tv_nsec) * 1e-9); -} -#endif - -BENCHMARK_NORETURN static void DiagnoseAndExit(const char* msg) { - std::cerr << "ERROR: " << msg << std::endl; - std::exit(EXIT_FAILURE); -} - -} // end namespace - -double ProcessCPUUsage() { -#if defined(BENCHMARK_OS_WINDOWS) - HANDLE proc = GetCurrentProcess(); - FILETIME creation_time; - FILETIME exit_time; - FILETIME kernel_time; - FILETIME user_time; - if (GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time, - &user_time)) - return MakeTime(kernel_time, user_time); - DiagnoseAndExit("GetProccessTimes() failed"); -#elif defined(BENCHMARK_OS_EMSCRIPTEN) - // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) returns 0 on Emscripten. - // Use Emscripten-specific API. Reported CPU time would be exactly the - // same as total time, but this is ok because there aren't long-latency - // syncronous system calls in Emscripten. - return emscripten_get_now() * 1e-3; -#elif defined(CLOCK_PROCESS_CPUTIME_ID) && !defined(BENCHMARK_OS_MACOSX) - // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. See - // https://github.com/google/benchmark/pull/292 - struct timespec spec; - if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &spec) == 0) - return MakeTime(spec); - DiagnoseAndExit("clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) failed"); -#else - struct rusage ru; - if (getrusage(RUSAGE_SELF, &ru) == 0) return MakeTime(ru); - DiagnoseAndExit("getrusage(RUSAGE_SELF, ...) failed"); -#endif -} - -double ThreadCPUUsage() { -#if defined(BENCHMARK_OS_WINDOWS) - HANDLE this_thread = GetCurrentThread(); - FILETIME creation_time; - FILETIME exit_time; - FILETIME kernel_time; - FILETIME user_time; - GetThreadTimes(this_thread, &creation_time, &exit_time, &kernel_time, - &user_time); - return MakeTime(kernel_time, user_time); -#elif defined(BENCHMARK_OS_MACOSX) - // FIXME We want to use clock_gettime, but its not available in MacOS 10.11. See - // https://github.com/google/benchmark/pull/292 - mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; - thread_basic_info_data_t info; - mach_port_t thread = pthread_mach_thread_np(pthread_self()); - if (thread_info(thread, THREAD_BASIC_INFO, (thread_info_t)&info, &count) == - KERN_SUCCESS) { - return MakeTime(info); - } - DiagnoseAndExit("ThreadCPUUsage() failed when evaluating thread_info"); -#elif defined(BENCHMARK_OS_EMSCRIPTEN) - // Emscripten doesn't support traditional threads - return ProcessCPUUsage(); -#elif defined(BENCHMARK_OS_RTEMS) - // RTEMS doesn't support CLOCK_THREAD_CPUTIME_ID. See - // https://github.com/RTEMS/rtems/blob/master/cpukit/posix/src/clockgettime.c - return ProcessCPUUsage(); -#elif defined(BENCHMARK_OS_SOLARIS) - struct rusage ru; - if (getrusage(RUSAGE_LWP, &ru) == 0) return MakeTime(ru); - DiagnoseAndExit("getrusage(RUSAGE_LWP, ...) failed"); -#elif defined(CLOCK_THREAD_CPUTIME_ID) - struct timespec ts; - if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) return MakeTime(ts); - DiagnoseAndExit("clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...) failed"); -#else -#error Per-thread timing is not available on your system. -#endif -} - -namespace { - -std::string DateTimeString(bool local) { - typedef std::chrono::system_clock Clock; - std::time_t now = Clock::to_time_t(Clock::now()); - const std::size_t kStorageSize = 128; - char storage[kStorageSize]; - std::size_t written; - - if (local) { -#if defined(BENCHMARK_OS_WINDOWS) - written = - std::strftime(storage, sizeof(storage), "%x %X", ::localtime(&now)); -#else - std::tm timeinfo; - ::localtime_r(&now, &timeinfo); - written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo); -#endif - } else { -#if defined(BENCHMARK_OS_WINDOWS) - written = std::strftime(storage, sizeof(storage), "%x %X", ::gmtime(&now)); -#else - std::tm timeinfo; - ::gmtime_r(&now, &timeinfo); - written = std::strftime(storage, sizeof(storage), "%F %T", &timeinfo); -#endif - } - CHECK(written < kStorageSize); - ((void)written); // prevent unused variable in optimized mode. - return std::string(storage); -} - -} // end namespace - -std::string LocalDateTimeString() { return DateTimeString(true); } - -} // end namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/timers.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/timers.h deleted file mode 100644 index 65606ccd93d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/src/timers.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef BENCHMARK_TIMERS_H -#define BENCHMARK_TIMERS_H - -#include -#include - -namespace benchmark { - -// Return the CPU usage of the current process -double ProcessCPUUsage(); - -// Return the CPU usage of the children of the current process -double ChildrenCPUUsage(); - -// Return the CPU usage of the current thread -double ThreadCPUUsage(); - -#if defined(HAVE_STEADY_CLOCK) -template -struct ChooseSteadyClock { - typedef std::chrono::high_resolution_clock type; -}; - -template <> -struct ChooseSteadyClock { - typedef std::chrono::steady_clock type; -}; -#endif - -struct ChooseClockType { -#if defined(HAVE_STEADY_CLOCK) - typedef ChooseSteadyClock<>::type type; -#else - typedef std::chrono::high_resolution_clock type; -#endif -}; - -inline double ChronoClockNow() { - typedef ChooseClockType::type ClockType; - using FpSeconds = std::chrono::duration; - return FpSeconds(ClockType::now().time_since_epoch()).count(); -} - -std::string LocalDateTimeString(); - -} // end namespace benchmark - -#endif // BENCHMARK_TIMERS_H diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/AssemblyTests.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/AssemblyTests.cmake deleted file mode 100644 index 3d078586f1d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/AssemblyTests.cmake +++ /dev/null @@ -1,46 +0,0 @@ - -include(split_list) - -set(ASM_TEST_FLAGS "") -check_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG) -if (BENCHMARK_HAS_O3_FLAG) - list(APPEND ASM_TEST_FLAGS -O3) -endif() - -check_cxx_compiler_flag(-g0 BENCHMARK_HAS_G0_FLAG) -if (BENCHMARK_HAS_G0_FLAG) - list(APPEND ASM_TEST_FLAGS -g0) -endif() - -check_cxx_compiler_flag(-fno-stack-protector BENCHMARK_HAS_FNO_STACK_PROTECTOR_FLAG) -if (BENCHMARK_HAS_FNO_STACK_PROTECTOR_FLAG) - list(APPEND ASM_TEST_FLAGS -fno-stack-protector) -endif() - -split_list(ASM_TEST_FLAGS) -string(TOUPPER "${CMAKE_CXX_COMPILER_ID}" ASM_TEST_COMPILER) - -macro(add_filecheck_test name) - cmake_parse_arguments(ARG "" "" "CHECK_PREFIXES" ${ARGV}) - add_library(${name} OBJECT ${name}.cc) - set_target_properties(${name} PROPERTIES COMPILE_FLAGS "-S ${ASM_TEST_FLAGS}") - set(ASM_OUTPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/${name}.s") - add_custom_target(copy_${name} ALL - COMMAND ${PROJECT_SOURCE_DIR}/tools/strip_asm.py - $ - ${ASM_OUTPUT_FILE} - BYPRODUCTS ${ASM_OUTPUT_FILE}) - add_dependencies(copy_${name} ${name}) - if (NOT ARG_CHECK_PREFIXES) - set(ARG_CHECK_PREFIXES "CHECK") - endif() - foreach(prefix ${ARG_CHECK_PREFIXES}) - add_test(NAME run_${name}_${prefix} - COMMAND - ${LLVM_FILECHECK_EXE} ${name}.cc - --input-file=${ASM_OUTPUT_FILE} - --check-prefixes=CHECK,CHECK-${ASM_TEST_COMPILER} - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) - endforeach() -endmacro() - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/BUILD b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/BUILD deleted file mode 100644 index 3f174c486f2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/BUILD +++ /dev/null @@ -1,65 +0,0 @@ -TEST_COPTS = [ - "-pedantic", - "-pedantic-errors", - "-std=c++11", - "-Wall", - "-Wextra", - "-Wshadow", -# "-Wshorten-64-to-32", - "-Wfloat-equal", - "-fstrict-aliasing", -] - -PER_SRC_COPTS = ({ - "cxx03_test.cc": ["-std=c++03"], - # Some of the issues with DoNotOptimize only occur when optimization is enabled - "donotoptimize_test.cc": ["-O3"], -}) - - -TEST_ARGS = ["--benchmark_min_time=0.01"] - -PER_SRC_TEST_ARGS = ({ - "user_counters_tabular_test.cc": ["--benchmark_counters_tabular=true"], -}) - -cc_library( - name = "output_test_helper", - testonly = 1, - srcs = ["output_test_helper.cc"], - hdrs = ["output_test.h"], - copts = TEST_COPTS, - deps = [ - "//:benchmark", - "//:benchmark_internal_headers", - ], -) - -[ - cc_test( - name = test_src[:-len(".cc")], - size = "small", - srcs = [test_src], - args = TEST_ARGS + PER_SRC_TEST_ARGS.get(test_src, []), - copts = TEST_COPTS + PER_SRC_COPTS.get(test_src, []), - deps = [ - ":output_test_helper", - "//:benchmark", - "//:benchmark_internal_headers", - "@com_google_googletest//:gtest", - ] + ( - ["@com_google_googletest//:gtest_main"] if (test_src[-len("gtest.cc"):] == "gtest.cc") else [] - ), - # FIXME: Add support for assembly tests to bazel. - # See Issue #556 - # https://github.com/google/benchmark/issues/556 - ) for test_src in glob(["*test.cc"], exclude = ["*_assembly_test.cc", "link_main_test.cc"]) -] - -cc_test( - name = "link_main_test", - size = "small", - srcs = ["link_main_test.cc"], - copts = TEST_COPTS, - deps = ["//:benchmark_main"], -) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/CMakeLists.txt b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/CMakeLists.txt deleted file mode 100644 index 030f35aae3f..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/CMakeLists.txt +++ /dev/null @@ -1,259 +0,0 @@ -# Enable the tests - -find_package(Threads REQUIRED) -include(CheckCXXCompilerFlag) - -# NOTE: Some tests use `` to perform the test. Therefore we must -# strip -DNDEBUG from the default CMake flags in DEBUG mode. -string(TOUPPER "${CMAKE_BUILD_TYPE}" uppercase_CMAKE_BUILD_TYPE) -if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" ) - add_definitions( -UNDEBUG ) - add_definitions(-DTEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS) - # Also remove /D NDEBUG to avoid MSVC warnings about conflicting defines. - foreach (flags_var_to_scrub - CMAKE_CXX_FLAGS_RELEASE - CMAKE_CXX_FLAGS_RELWITHDEBINFO - CMAKE_CXX_FLAGS_MINSIZEREL - CMAKE_C_FLAGS_RELEASE - CMAKE_C_FLAGS_RELWITHDEBINFO - CMAKE_C_FLAGS_MINSIZEREL) - string (REGEX REPLACE "(^| )[/-]D *NDEBUG($| )" " " - "${flags_var_to_scrub}" "${${flags_var_to_scrub}}") - endforeach() -endif() - -check_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG) -set(BENCHMARK_O3_FLAG "") -if (BENCHMARK_HAS_O3_FLAG) - set(BENCHMARK_O3_FLAG "-O3") -endif() - -# NOTE: These flags must be added after find_package(Threads REQUIRED) otherwise -# they will break the configuration check. -if (DEFINED BENCHMARK_CXX_LINKER_FLAGS) - list(APPEND CMAKE_EXE_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) -endif() - -add_library(output_test_helper STATIC output_test_helper.cc output_test.h) - -macro(compile_benchmark_test name) - add_executable(${name} "${name}.cc") - target_link_libraries(${name} benchmark ${CMAKE_THREAD_LIBS_INIT}) -endmacro(compile_benchmark_test) - -macro(compile_benchmark_test_with_main name) - add_executable(${name} "${name}.cc") - target_link_libraries(${name} benchmark_main) -endmacro(compile_benchmark_test_with_main) - -macro(compile_output_test name) - add_executable(${name} "${name}.cc" output_test.h) - target_link_libraries(${name} output_test_helper benchmark - ${BENCHMARK_CXX_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) -endmacro(compile_output_test) - -# Demonstration executable -compile_benchmark_test(benchmark_test) -add_test(benchmark benchmark_test --benchmark_min_time=0.01) - -compile_benchmark_test(filter_test) -macro(add_filter_test name filter expect) - add_test(${name} filter_test --benchmark_min_time=0.01 --benchmark_filter=${filter} ${expect}) - add_test(${name}_list_only filter_test --benchmark_list_tests --benchmark_filter=${filter} ${expect}) -endmacro(add_filter_test) - -add_filter_test(filter_simple "Foo" 3) -add_filter_test(filter_simple_negative "-Foo" 2) -add_filter_test(filter_suffix "BM_.*" 4) -add_filter_test(filter_suffix_negative "-BM_.*" 1) -add_filter_test(filter_regex_all ".*" 5) -add_filter_test(filter_regex_all_negative "-.*" 0) -add_filter_test(filter_regex_blank "" 5) -add_filter_test(filter_regex_blank_negative "-" 0) -add_filter_test(filter_regex_none "monkey" 0) -add_filter_test(filter_regex_none_negative "-monkey" 5) -add_filter_test(filter_regex_wildcard ".*Foo.*" 3) -add_filter_test(filter_regex_wildcard_negative "-.*Foo.*" 2) -add_filter_test(filter_regex_begin "^BM_.*" 4) -add_filter_test(filter_regex_begin_negative "-^BM_.*" 1) -add_filter_test(filter_regex_begin2 "^N" 1) -add_filter_test(filter_regex_begin2_negative "-^N" 4) -add_filter_test(filter_regex_end ".*Ba$" 1) -add_filter_test(filter_regex_end_negative "-.*Ba$" 4) - -compile_benchmark_test(options_test) -add_test(options_benchmarks options_test --benchmark_min_time=0.01) - -compile_benchmark_test(basic_test) -add_test(basic_benchmark basic_test --benchmark_min_time=0.01) - -compile_benchmark_test(diagnostics_test) -add_test(diagnostics_test diagnostics_test --benchmark_min_time=0.01) - -compile_benchmark_test(skip_with_error_test) -add_test(skip_with_error_test skip_with_error_test --benchmark_min_time=0.01) - -compile_benchmark_test(donotoptimize_test) -# Some of the issues with DoNotOptimize only occur when optimization is enabled -check_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG) -if (BENCHMARK_HAS_O3_FLAG) - set_target_properties(donotoptimize_test PROPERTIES COMPILE_FLAGS "-O3") -endif() -add_test(donotoptimize_test donotoptimize_test --benchmark_min_time=0.01) - -compile_benchmark_test(fixture_test) -add_test(fixture_test fixture_test --benchmark_min_time=0.01) - -compile_benchmark_test(register_benchmark_test) -add_test(register_benchmark_test register_benchmark_test --benchmark_min_time=0.01) - -compile_benchmark_test(map_test) -add_test(map_test map_test --benchmark_min_time=0.01) - -compile_benchmark_test(multiple_ranges_test) -add_test(multiple_ranges_test multiple_ranges_test --benchmark_min_time=0.01) - -compile_benchmark_test_with_main(link_main_test) -add_test(link_main_test link_main_test --benchmark_min_time=0.01) - -compile_output_test(reporter_output_test) -add_test(reporter_output_test reporter_output_test --benchmark_min_time=0.01) - -compile_output_test(templated_fixture_test) -add_test(templated_fixture_test templated_fixture_test --benchmark_min_time=0.01) - -compile_output_test(user_counters_test) -add_test(user_counters_test user_counters_test --benchmark_min_time=0.01) - -compile_output_test(internal_threading_test) -add_test(internal_threading_test internal_threading_test --benchmark_min_time=0.01) - -compile_output_test(report_aggregates_only_test) -add_test(report_aggregates_only_test report_aggregates_only_test --benchmark_min_time=0.01) - -compile_output_test(display_aggregates_only_test) -add_test(display_aggregates_only_test display_aggregates_only_test --benchmark_min_time=0.01) - -compile_output_test(user_counters_tabular_test) -add_test(user_counters_tabular_test user_counters_tabular_test --benchmark_counters_tabular=true --benchmark_min_time=0.01) - -compile_output_test(user_counters_thousands_test) -add_test(user_counters_thousands_test user_counters_thousands_test --benchmark_min_time=0.01) - -compile_output_test(memory_manager_test) -add_test(memory_manager_test memory_manager_test --benchmark_min_time=0.01) - -check_cxx_compiler_flag(-std=c++03 BENCHMARK_HAS_CXX03_FLAG) -if (BENCHMARK_HAS_CXX03_FLAG) - compile_benchmark_test(cxx03_test) - set_target_properties(cxx03_test - PROPERTIES - COMPILE_FLAGS "-std=c++03") - # libstdc++ provides different definitions within between dialects. When - # LTO is enabled and -Werror is specified GCC diagnoses this ODR violation - # causing the test to fail to compile. To prevent this we explicitly disable - # the warning. - check_cxx_compiler_flag(-Wno-odr BENCHMARK_HAS_WNO_ODR) - if (BENCHMARK_ENABLE_LTO AND BENCHMARK_HAS_WNO_ODR) - set_target_properties(cxx03_test - PROPERTIES - LINK_FLAGS "-Wno-odr") - endif() - add_test(cxx03 cxx03_test --benchmark_min_time=0.01) -endif() - -# Attempt to work around flaky test failures when running on Appveyor servers. -if (DEFINED ENV{APPVEYOR}) - set(COMPLEXITY_MIN_TIME "0.5") -else() - set(COMPLEXITY_MIN_TIME "0.01") -endif() -compile_output_test(complexity_test) -add_test(complexity_benchmark complexity_test --benchmark_min_time=${COMPLEXITY_MIN_TIME}) - -############################################################################### -# GoogleTest Unit Tests -############################################################################### - -if (BENCHMARK_ENABLE_GTEST_TESTS) - macro(compile_gtest name) - add_executable(${name} "${name}.cc") - target_link_libraries(${name} benchmark - gmock_main ${CMAKE_THREAD_LIBS_INIT}) - endmacro(compile_gtest) - - macro(add_gtest name) - compile_gtest(${name}) - add_test(${name} ${name}) - endmacro() - - add_gtest(benchmark_gtest) - add_gtest(benchmark_name_gtest) - add_gtest(commandlineflags_gtest) - add_gtest(statistics_gtest) - add_gtest(string_util_gtest) -endif(BENCHMARK_ENABLE_GTEST_TESTS) - -############################################################################### -# Assembly Unit Tests -############################################################################### - -if (BENCHMARK_ENABLE_ASSEMBLY_TESTS) - if (NOT LLVM_FILECHECK_EXE) - message(FATAL_ERROR "LLVM FileCheck is required when including this file") - endif() - include(AssemblyTests.cmake) - add_filecheck_test(donotoptimize_assembly_test) - add_filecheck_test(state_assembly_test) - add_filecheck_test(clobber_memory_assembly_test) -endif() - - - -############################################################################### -# Code Coverage Configuration -############################################################################### - -# Add the coverage command(s) -if(CMAKE_BUILD_TYPE) - string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER) -endif() -if (${CMAKE_BUILD_TYPE_LOWER} MATCHES "coverage") - find_program(GCOV gcov) - find_program(LCOV lcov) - find_program(GENHTML genhtml) - find_program(CTEST ctest) - if (GCOV AND LCOV AND GENHTML AND CTEST AND HAVE_CXX_FLAG_COVERAGE) - add_custom_command( - OUTPUT ${CMAKE_BINARY_DIR}/lcov/index.html - COMMAND ${LCOV} -q -z -d . - COMMAND ${LCOV} -q --no-external -c -b "${CMAKE_SOURCE_DIR}" -d . -o before.lcov -i - COMMAND ${CTEST} --force-new-ctest-process - COMMAND ${LCOV} -q --no-external -c -b "${CMAKE_SOURCE_DIR}" -d . -o after.lcov - COMMAND ${LCOV} -q -a before.lcov -a after.lcov --output-file final.lcov - COMMAND ${LCOV} -q -r final.lcov "'${CMAKE_SOURCE_DIR}/test/*'" -o final.lcov - COMMAND ${GENHTML} final.lcov -o lcov --demangle-cpp --sort -p "${CMAKE_BINARY_DIR}" -t benchmark - DEPENDS filter_test benchmark_test options_test basic_test fixture_test cxx03_test complexity_test - WORKING_DIRECTORY ${CMAKE_BINARY_DIR} - COMMENT "Running LCOV" - ) - add_custom_target(coverage - DEPENDS ${CMAKE_BINARY_DIR}/lcov/index.html - COMMENT "LCOV report at lcov/index.html" - ) - message(STATUS "Coverage command added") - else() - if (HAVE_CXX_FLAG_COVERAGE) - set(CXX_FLAG_COVERAGE_MESSAGE supported) - else() - set(CXX_FLAG_COVERAGE_MESSAGE unavailable) - endif() - message(WARNING - "Coverage not available:\n" - " gcov: ${GCOV}\n" - " lcov: ${LCOV}\n" - " genhtml: ${GENHTML}\n" - " ctest: ${CTEST}\n" - " --coverage flag: ${CXX_FLAG_COVERAGE_MESSAGE}") - endif() -endif() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/basic_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/basic_test.cc deleted file mode 100644 index 5f3dd1a3ee9..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/basic_test.cc +++ /dev/null @@ -1,136 +0,0 @@ - -#include "benchmark/benchmark.h" - -#define BASIC_BENCHMARK_TEST(x) BENCHMARK(x)->Arg(8)->Arg(512)->Arg(8192) - -void BM_empty(benchmark::State& state) { - for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); - } -} -BENCHMARK(BM_empty); -BENCHMARK(BM_empty)->ThreadPerCpu(); - -void BM_spin_empty(benchmark::State& state) { - for (auto _ : state) { - for (int x = 0; x < state.range(0); ++x) { - benchmark::DoNotOptimize(x); - } - } -} -BASIC_BENCHMARK_TEST(BM_spin_empty); -BASIC_BENCHMARK_TEST(BM_spin_empty)->ThreadPerCpu(); - -void BM_spin_pause_before(benchmark::State& state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - } -} -BASIC_BENCHMARK_TEST(BM_spin_pause_before); -BASIC_BENCHMARK_TEST(BM_spin_pause_before)->ThreadPerCpu(); - -void BM_spin_pause_during(benchmark::State& state) { - for (auto _ : state) { - state.PauseTiming(); - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - state.ResumeTiming(); - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - } -} -BASIC_BENCHMARK_TEST(BM_spin_pause_during); -BASIC_BENCHMARK_TEST(BM_spin_pause_during)->ThreadPerCpu(); - -void BM_pause_during(benchmark::State& state) { - for (auto _ : state) { - state.PauseTiming(); - state.ResumeTiming(); - } -} -BENCHMARK(BM_pause_during); -BENCHMARK(BM_pause_during)->ThreadPerCpu(); -BENCHMARK(BM_pause_during)->UseRealTime(); -BENCHMARK(BM_pause_during)->UseRealTime()->ThreadPerCpu(); - -void BM_spin_pause_after(benchmark::State& state) { - for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - } - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } -} -BASIC_BENCHMARK_TEST(BM_spin_pause_after); -BASIC_BENCHMARK_TEST(BM_spin_pause_after)->ThreadPerCpu(); - -void BM_spin_pause_before_and_after(benchmark::State& state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } - } - for (int i = 0; i < state.range(0); ++i) { - benchmark::DoNotOptimize(i); - } -} -BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after); -BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after)->ThreadPerCpu(); - -void BM_empty_stop_start(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_empty_stop_start); -BENCHMARK(BM_empty_stop_start)->ThreadPerCpu(); - - -void BM_KeepRunning(benchmark::State& state) { - benchmark::IterationCount iter_count = 0; - assert(iter_count == state.iterations()); - while (state.KeepRunning()) { - ++iter_count; - } - assert(iter_count == state.iterations()); -} -BENCHMARK(BM_KeepRunning); - -void BM_KeepRunningBatch(benchmark::State& state) { - // Choose a prime batch size to avoid evenly dividing max_iterations. - const benchmark::IterationCount batch_size = 101; - benchmark::IterationCount iter_count = 0; - while (state.KeepRunningBatch(batch_size)) { - iter_count += batch_size; - } - assert(state.iterations() == iter_count); -} -BENCHMARK(BM_KeepRunningBatch); - -void BM_RangedFor(benchmark::State& state) { - benchmark::IterationCount iter_count = 0; - for (auto _ : state) { - ++iter_count; - } - assert(iter_count == state.max_iterations); -} -BENCHMARK(BM_RangedFor); - -// Ensure that StateIterator provides all the necessary typedefs required to -// instantiate std::iterator_traits. -static_assert(std::is_same< - typename std::iterator_traits::value_type, - typename benchmark::State::StateIterator::value_type>::value, ""); - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/benchmark_gtest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/benchmark_gtest.cc deleted file mode 100644 index 9557b20ec7d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/benchmark_gtest.cc +++ /dev/null @@ -1,128 +0,0 @@ -#include - -#include "../src/benchmark_register.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" - -namespace benchmark { -namespace internal { -namespace { - -TEST(AddRangeTest, Simple) { - std::vector dst; - AddRange(&dst, 1, 2, 2); - EXPECT_THAT(dst, testing::ElementsAre(1, 2)); -} - -TEST(AddRangeTest, Simple64) { - std::vector dst; - AddRange(&dst, static_cast(1), static_cast(2), 2); - EXPECT_THAT(dst, testing::ElementsAre(1, 2)); -} - -TEST(AddRangeTest, Advanced) { - std::vector dst; - AddRange(&dst, 5, 15, 2); - EXPECT_THAT(dst, testing::ElementsAre(5, 8, 15)); -} - -TEST(AddRangeTest, Advanced64) { - std::vector dst; - AddRange(&dst, static_cast(5), static_cast(15), 2); - EXPECT_THAT(dst, testing::ElementsAre(5, 8, 15)); -} - -TEST(AddRangeTest, FullRange8) { - std::vector dst; - AddRange(&dst, int8_t{1}, std::numeric_limits::max(), 8); - EXPECT_THAT(dst, testing::ElementsAre(1, 8, 64, 127)); -} - -TEST(AddRangeTest, FullRange64) { - std::vector dst; - AddRange(&dst, int64_t{1}, std::numeric_limits::max(), 1024); - EXPECT_THAT( - dst, testing::ElementsAre(1LL, 1024LL, 1048576LL, 1073741824LL, - 1099511627776LL, 1125899906842624LL, - 1152921504606846976LL, 9223372036854775807LL)); -} - -TEST(AddRangeTest, NegativeRanges) { - std::vector dst; - AddRange(&dst, -8, 0, 2); - EXPECT_THAT(dst, testing::ElementsAre(-8, -4, -2, -1, 0)); -} - -TEST(AddRangeTest, StrictlyNegative) { - std::vector dst; - AddRange(&dst, -8, -1, 2); - EXPECT_THAT(dst, testing::ElementsAre(-8, -4, -2, -1)); -} - -TEST(AddRangeTest, SymmetricNegativeRanges) { - std::vector dst; - AddRange(&dst, -8, 8, 2); - EXPECT_THAT(dst, testing::ElementsAre(-8, -4, -2, -1, 0, 1, 2, 4, 8)); -} - -TEST(AddRangeTest, SymmetricNegativeRangesOddMult) { - std::vector dst; - AddRange(&dst, -30, 32, 5); - EXPECT_THAT(dst, testing::ElementsAre(-30, -25, -5, -1, 0, 1, 5, 25, 32)); -} - -TEST(AddRangeTest, NegativeRangesAsymmetric) { - std::vector dst; - AddRange(&dst, -3, 5, 2); - EXPECT_THAT(dst, testing::ElementsAre(-3, -2, -1, 0, 1, 2, 4, 5)); -} - -TEST(AddRangeTest, NegativeRangesLargeStep) { - // Always include -1, 0, 1 when crossing zero. - std::vector dst; - AddRange(&dst, -8, 8, 10); - EXPECT_THAT(dst, testing::ElementsAre(-8, -1, 0, 1, 8)); -} - -TEST(AddRangeTest, ZeroOnlyRange) { - std::vector dst; - AddRange(&dst, 0, 0, 2); - EXPECT_THAT(dst, testing::ElementsAre(0)); -} - -TEST(AddRangeTest, NegativeRange64) { - std::vector dst; - AddRange(&dst, -4, 4, 2); - EXPECT_THAT(dst, testing::ElementsAre(-4, -2, -1, 0, 1, 2, 4)); -} - -TEST(AddRangeTest, NegativeRangePreservesExistingOrder) { - // If elements already exist in the range, ensure we don't change - // their ordering by adding negative values. - std::vector dst = {1, 2, 3}; - AddRange(&dst, -2, 2, 2); - EXPECT_THAT(dst, testing::ElementsAre(1, 2, 3, -2, -1, 0, 1, 2)); -} - -TEST(AddRangeTest, FullNegativeRange64) { - std::vector dst; - const auto min = std::numeric_limits::min(); - const auto max = std::numeric_limits::max(); - AddRange(&dst, min, max, 1024); - EXPECT_THAT( - dst, testing::ElementsAreArray(std::vector{ - min, -1152921504606846976LL, -1125899906842624LL, - -1099511627776LL, -1073741824LL, -1048576LL, -1024LL, -1LL, 0LL, - 1LL, 1024LL, 1048576LL, 1073741824LL, 1099511627776LL, - 1125899906842624LL, 1152921504606846976LL, max})); -} - -TEST(AddRangeTest, Simple8) { - std::vector dst; - AddRange(&dst, 1, 8, 2); - EXPECT_THAT(dst, testing::ElementsAre(1, 2, 4, 8)); -} - -} // namespace -} // namespace internal -} // namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/benchmark_name_gtest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/benchmark_name_gtest.cc deleted file mode 100644 index afb401c1f53..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/benchmark_name_gtest.cc +++ /dev/null @@ -1,74 +0,0 @@ -#include "benchmark/benchmark.h" -#include "gtest/gtest.h" - -namespace { - -using namespace benchmark; -using namespace benchmark::internal; - -TEST(BenchmarkNameTest, Empty) { - const auto name = BenchmarkName(); - EXPECT_EQ(name.str(), std::string()); -} - -TEST(BenchmarkNameTest, FunctionName) { - auto name = BenchmarkName(); - name.function_name = "function_name"; - EXPECT_EQ(name.str(), "function_name"); -} - -TEST(BenchmarkNameTest, FunctionNameAndArgs) { - auto name = BenchmarkName(); - name.function_name = "function_name"; - name.args = "some_args:3/4/5"; - EXPECT_EQ(name.str(), "function_name/some_args:3/4/5"); -} - -TEST(BenchmarkNameTest, MinTime) { - auto name = BenchmarkName(); - name.function_name = "function_name"; - name.args = "some_args:3/4"; - name.min_time = "min_time:3.4s"; - EXPECT_EQ(name.str(), "function_name/some_args:3/4/min_time:3.4s"); -} - -TEST(BenchmarkNameTest, Iterations) { - auto name = BenchmarkName(); - name.function_name = "function_name"; - name.min_time = "min_time:3.4s"; - name.iterations = "iterations:42"; - EXPECT_EQ(name.str(), "function_name/min_time:3.4s/iterations:42"); -} - -TEST(BenchmarkNameTest, Repetitions) { - auto name = BenchmarkName(); - name.function_name = "function_name"; - name.min_time = "min_time:3.4s"; - name.repetitions = "repetitions:24"; - EXPECT_EQ(name.str(), "function_name/min_time:3.4s/repetitions:24"); -} - -TEST(BenchmarkNameTest, TimeType) { - auto name = BenchmarkName(); - name.function_name = "function_name"; - name.min_time = "min_time:3.4s"; - name.time_type = "hammer_time"; - EXPECT_EQ(name.str(), "function_name/min_time:3.4s/hammer_time"); -} - -TEST(BenchmarkNameTest, Threads) { - auto name = BenchmarkName(); - name.function_name = "function_name"; - name.min_time = "min_time:3.4s"; - name.threads = "threads:256"; - EXPECT_EQ(name.str(), "function_name/min_time:3.4s/threads:256"); -} - -TEST(BenchmarkNameTest, TestEmptyFunctionName) { - auto name = BenchmarkName(); - name.args = "first:3/second:4"; - name.threads = "threads:22"; - EXPECT_EQ(name.str(), "first:3/second:4/threads:22"); -} - -} // end namespace diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/benchmark_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/benchmark_test.cc deleted file mode 100644 index 3cd4f5565fa..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/benchmark_test.cc +++ /dev/null @@ -1,245 +0,0 @@ -#include "benchmark/benchmark.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(__GNUC__) -#define BENCHMARK_NOINLINE __attribute__((noinline)) -#else -#define BENCHMARK_NOINLINE -#endif - -namespace { - -int BENCHMARK_NOINLINE Factorial(uint32_t n) { - return (n == 1) ? 1 : n * Factorial(n - 1); -} - -double CalculatePi(int depth) { - double pi = 0.0; - for (int i = 0; i < depth; ++i) { - double numerator = static_cast(((i % 2) * 2) - 1); - double denominator = static_cast((2 * i) - 1); - pi += numerator / denominator; - } - return (pi - 1.0) * 4; -} - -std::set ConstructRandomSet(int64_t size) { - std::set s; - for (int i = 0; i < size; ++i) s.insert(s.end(), i); - return s; -} - -std::mutex test_vector_mu; -std::vector* test_vector = nullptr; - -} // end namespace - -static void BM_Factorial(benchmark::State& state) { - int fac_42 = 0; - for (auto _ : state) fac_42 = Factorial(8); - // Prevent compiler optimizations - std::stringstream ss; - ss << fac_42; - state.SetLabel(ss.str()); -} -BENCHMARK(BM_Factorial); -BENCHMARK(BM_Factorial)->UseRealTime(); - -static void BM_CalculatePiRange(benchmark::State& state) { - double pi = 0.0; - for (auto _ : state) pi = CalculatePi(static_cast(state.range(0))); - std::stringstream ss; - ss << pi; - state.SetLabel(ss.str()); -} -BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024); - -static void BM_CalculatePi(benchmark::State& state) { - static const int depth = 1024; - for (auto _ : state) { - benchmark::DoNotOptimize(CalculatePi(static_cast(depth))); - } -} -BENCHMARK(BM_CalculatePi)->Threads(8); -BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32); -BENCHMARK(BM_CalculatePi)->ThreadPerCpu(); - -static void BM_SetInsert(benchmark::State& state) { - std::set data; - for (auto _ : state) { - state.PauseTiming(); - data = ConstructRandomSet(state.range(0)); - state.ResumeTiming(); - for (int j = 0; j < state.range(1); ++j) data.insert(rand()); - } - state.SetItemsProcessed(state.iterations() * state.range(1)); - state.SetBytesProcessed(state.iterations() * state.range(1) * sizeof(int)); -} - -// Test many inserts at once to reduce the total iterations needed. Otherwise, the slower, -// non-timed part of each iteration will make the benchmark take forever. -BENCHMARK(BM_SetInsert)->Ranges({{1 << 10, 8 << 10}, {128, 512}}); - -template -static void BM_Sequential(benchmark::State& state) { - ValueType v = 42; - for (auto _ : state) { - Container c; - for (int64_t i = state.range(0); --i;) c.push_back(v); - } - const int64_t items_processed = state.iterations() * state.range(0); - state.SetItemsProcessed(items_processed); - state.SetBytesProcessed(items_processed * sizeof(v)); -} -BENCHMARK_TEMPLATE2(BM_Sequential, std::vector, int) - ->Range(1 << 0, 1 << 10); -BENCHMARK_TEMPLATE(BM_Sequential, std::list)->Range(1 << 0, 1 << 10); -// Test the variadic version of BENCHMARK_TEMPLATE in C++11 and beyond. -#ifdef BENCHMARK_HAS_CXX11 -BENCHMARK_TEMPLATE(BM_Sequential, std::vector, int)->Arg(512); -#endif - -static void BM_StringCompare(benchmark::State& state) { - size_t len = static_cast(state.range(0)); - std::string s1(len, '-'); - std::string s2(len, '-'); - for (auto _ : state) benchmark::DoNotOptimize(s1.compare(s2)); -} -BENCHMARK(BM_StringCompare)->Range(1, 1 << 20); - -static void BM_SetupTeardown(benchmark::State& state) { - if (state.thread_index == 0) { - // No need to lock test_vector_mu here as this is running single-threaded. - test_vector = new std::vector(); - } - int i = 0; - for (auto _ : state) { - std::lock_guard l(test_vector_mu); - if (i % 2 == 0) - test_vector->push_back(i); - else - test_vector->pop_back(); - ++i; - } - if (state.thread_index == 0) { - delete test_vector; - } -} -BENCHMARK(BM_SetupTeardown)->ThreadPerCpu(); - -static void BM_LongTest(benchmark::State& state) { - double tracker = 0.0; - for (auto _ : state) { - for (int i = 0; i < state.range(0); ++i) - benchmark::DoNotOptimize(tracker += i); - } -} -BENCHMARK(BM_LongTest)->Range(1 << 16, 1 << 28); - -static void BM_ParallelMemset(benchmark::State& state) { - int64_t size = state.range(0) / static_cast(sizeof(int)); - int thread_size = static_cast(size) / state.threads; - int from = thread_size * state.thread_index; - int to = from + thread_size; - - if (state.thread_index == 0) { - test_vector = new std::vector(static_cast(size)); - } - - for (auto _ : state) { - for (int i = from; i < to; i++) { - // No need to lock test_vector_mu as ranges - // do not overlap between threads. - benchmark::DoNotOptimize(test_vector->at(i) = 1); - } - } - - if (state.thread_index == 0) { - delete test_vector; - } -} -BENCHMARK(BM_ParallelMemset)->Arg(10 << 20)->ThreadRange(1, 4); - -static void BM_ManualTiming(benchmark::State& state) { - int64_t slept_for = 0; - int64_t microseconds = state.range(0); - std::chrono::duration sleep_duration{ - static_cast(microseconds)}; - - for (auto _ : state) { - auto start = std::chrono::high_resolution_clock::now(); - // Simulate some useful workload with a sleep - std::this_thread::sleep_for( - std::chrono::duration_cast(sleep_duration)); - auto end = std::chrono::high_resolution_clock::now(); - - auto elapsed = - std::chrono::duration_cast>(end - start); - - state.SetIterationTime(elapsed.count()); - slept_for += microseconds; - } - state.SetItemsProcessed(slept_for); -} -BENCHMARK(BM_ManualTiming)->Range(1, 1 << 14)->UseRealTime(); -BENCHMARK(BM_ManualTiming)->Range(1, 1 << 14)->UseManualTime(); - -#ifdef BENCHMARK_HAS_CXX11 - -template -void BM_with_args(benchmark::State& state, Args&&...) { - for (auto _ : state) { - } -} -BENCHMARK_CAPTURE(BM_with_args, int_test, 42, 43, 44); -BENCHMARK_CAPTURE(BM_with_args, string_and_pair_test, std::string("abc"), - std::pair(42, 3.8)); - -void BM_non_template_args(benchmark::State& state, int, double) { - while(state.KeepRunning()) {} -} -BENCHMARK_CAPTURE(BM_non_template_args, basic_test, 0, 0); - -#endif // BENCHMARK_HAS_CXX11 - -static void BM_DenseThreadRanges(benchmark::State& st) { - switch (st.range(0)) { - case 1: - assert(st.threads == 1 || st.threads == 2 || st.threads == 3); - break; - case 2: - assert(st.threads == 1 || st.threads == 3 || st.threads == 4); - break; - case 3: - assert(st.threads == 5 || st.threads == 8 || st.threads == 11 || - st.threads == 14); - break; - default: - assert(false && "Invalid test case number"); - } - while (st.KeepRunning()) { - } -} -BENCHMARK(BM_DenseThreadRanges)->Arg(1)->DenseThreadRange(1, 3); -BENCHMARK(BM_DenseThreadRanges)->Arg(2)->DenseThreadRange(1, 4, 2); -BENCHMARK(BM_DenseThreadRanges)->Arg(3)->DenseThreadRange(5, 14, 3); - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/clobber_memory_assembly_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/clobber_memory_assembly_test.cc deleted file mode 100644 index f41911a39ce..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/clobber_memory_assembly_test.cc +++ /dev/null @@ -1,64 +0,0 @@ -#include - -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wreturn-type" -#endif - -extern "C" { - -extern int ExternInt; -extern int ExternInt2; -extern int ExternInt3; - -} - -// CHECK-LABEL: test_basic: -extern "C" void test_basic() { - int x; - benchmark::DoNotOptimize(&x); - x = 101; - benchmark::ClobberMemory(); - // CHECK: leaq [[DEST:[^,]+]], %rax - // CHECK: movl $101, [[DEST]] - // CHECK: ret -} - -// CHECK-LABEL: test_redundant_store: -extern "C" void test_redundant_store() { - ExternInt = 3; - benchmark::ClobberMemory(); - ExternInt = 51; - // CHECK-DAG: ExternInt - // CHECK-DAG: movl $3 - // CHECK: movl $51 -} - -// CHECK-LABEL: test_redundant_read: -extern "C" void test_redundant_read() { - int x; - benchmark::DoNotOptimize(&x); - x = ExternInt; - benchmark::ClobberMemory(); - x = ExternInt2; - // CHECK: leaq [[DEST:[^,]+]], %rax - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, [[DEST]] - // CHECK-NOT: ExternInt2 - // CHECK: ret -} - -// CHECK-LABEL: test_redundant_read2: -extern "C" void test_redundant_read2() { - int x; - benchmark::DoNotOptimize(&x); - x = ExternInt; - benchmark::ClobberMemory(); - x = ExternInt2; - benchmark::ClobberMemory(); - // CHECK: leaq [[DEST:[^,]+]], %rax - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, [[DEST]] - // CHECK: ExternInt2(%rip) - // CHECK: movl %eax, [[DEST]] - // CHECK: ret -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/commandlineflags_gtest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/commandlineflags_gtest.cc deleted file mode 100644 index 5460778c488..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/commandlineflags_gtest.cc +++ /dev/null @@ -1,78 +0,0 @@ -#include - -#include "../src/commandlineflags.h" -#include "../src/internal_macros.h" -#include "gtest/gtest.h" - -namespace benchmark { -namespace { - -#if defined(BENCHMARK_OS_WINDOWS) -int setenv(const char* name, const char* value, int overwrite) { - if (!overwrite) { - // NOTE: getenv_s is far superior but not available under mingw. - char* env_value = getenv(name); - if (env_value == nullptr) { - return -1; - } - } - return _putenv_s(name, value); -} - -int unsetenv(const char* name) { - return _putenv_s(name, ""); -} - -#endif // BENCHMARK_OS_WINDOWS - -TEST(BoolFromEnv, Default) { - ASSERT_EQ(unsetenv("BENCHMARK_NOT_IN_ENV"), 0); - EXPECT_EQ(BoolFromEnv("not_in_env", true), true); -} - -TEST(BoolFromEnv, False) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "0", 1), 0); - EXPECT_EQ(BoolFromEnv("in_env", true), false); - unsetenv("BENCHMARK_IN_ENV"); -} - -TEST(BoolFromEnv, True) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "1", 1), 0); - EXPECT_EQ(BoolFromEnv("in_env", false), true); - unsetenv("BENCHMARK_IN_ENV"); - - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "foo", 1), 0); - EXPECT_EQ(BoolFromEnv("in_env", false), true); - unsetenv("BENCHMARK_IN_ENV"); -} - -TEST(Int32FromEnv, NotInEnv) { - ASSERT_EQ(unsetenv("BENCHMARK_NOT_IN_ENV"), 0); - EXPECT_EQ(Int32FromEnv("not_in_env", 42), 42); -} - -TEST(Int32FromEnv, InvalidInteger) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "foo", 1), 0); - EXPECT_EQ(Int32FromEnv("in_env", 42), 42); - ASSERT_EQ(unsetenv("BENCHMARK_IN_ENV"), 0); -} - -TEST(Int32FromEnv, ValidInteger) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "42", 1), 0); - EXPECT_EQ(Int32FromEnv("in_env", 64), 42); - unsetenv("BENCHMARK_IN_ENV"); -} - -TEST(StringFromEnv, Default) { - ASSERT_EQ(unsetenv("BENCHMARK_NOT_IN_ENV"), 0); - EXPECT_STREQ(StringFromEnv("not_in_env", "foo"), "foo"); -} - -TEST(StringFromEnv, Valid) { - ASSERT_EQ(setenv("BENCHMARK_IN_ENV", "foo", 1), 0); - EXPECT_STREQ(StringFromEnv("in_env", "bar"), "foo"); - unsetenv("BENCHMARK_IN_ENV"); -} - -} // namespace -} // namespace benchmark diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/complexity_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/complexity_test.cc deleted file mode 100644 index d4febbbc15e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/complexity_test.cc +++ /dev/null @@ -1,211 +0,0 @@ -#undef NDEBUG -#include -#include -#include -#include -#include -#include "benchmark/benchmark.h" -#include "output_test.h" - -namespace { - -#define ADD_COMPLEXITY_CASES(...) \ - int CONCAT(dummy, __LINE__) = AddComplexityTest(__VA_ARGS__) - -int AddComplexityTest(std::string test_name, std::string big_o_test_name, - std::string rms_test_name, std::string big_o) { - SetSubstitutions({{"%name", test_name}, - {"%bigo_name", big_o_test_name}, - {"%rms_name", rms_test_name}, - {"%bigo_str", "[ ]* %float " + big_o}, - {"%bigo", big_o}, - {"%rms", "[ ]*[0-9]+ %"}}); - AddCases( - TC_ConsoleOut, - {{"^%bigo_name %bigo_str %bigo_str[ ]*$"}, - {"^%bigo_name", MR_Not}, // Assert we we didn't only matched a name. - {"^%rms_name %rms %rms[ ]*$", MR_Next}}); - AddCases(TC_JSONOut, {{"\"name\": \"%bigo_name\",$"}, - {"\"run_name\": \"%name\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": %int,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"BigO\",$", MR_Next}, - {"\"cpu_coefficient\": %float,$", MR_Next}, - {"\"real_coefficient\": %float,$", MR_Next}, - {"\"big_o\": \"%bigo\",$", MR_Next}, - {"\"time_unit\": \"ns\"$", MR_Next}, - {"}", MR_Next}, - {"\"name\": \"%rms_name\",$"}, - {"\"run_name\": \"%name\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": %int,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"RMS\",$", MR_Next}, - {"\"rms\": %float$", MR_Next}, - {"}", MR_Next}}); - AddCases(TC_CSVOut, {{"^\"%bigo_name\",,%float,%float,%bigo,,,,,$"}, - {"^\"%bigo_name\"", MR_Not}, - {"^\"%rms_name\",,%float,%float,,,,,,$", MR_Next}}); - return 0; -} - -} // end namespace - -// ========================================================================= // -// --------------------------- Testing BigO O(1) --------------------------- // -// ========================================================================= // - -void BM_Complexity_O1(benchmark::State& state) { - for (auto _ : state) { - for (int i = 0; i < 1024; ++i) { - benchmark::DoNotOptimize(&i); - } - } - state.SetComplexityN(state.range(0)); -} -BENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity(benchmark::o1); -BENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity(); -BENCHMARK(BM_Complexity_O1) - ->Range(1, 1 << 18) - ->Complexity([](benchmark::IterationCount) { return 1.0; }); - -const char *one_test_name = "BM_Complexity_O1"; -const char *big_o_1_test_name = "BM_Complexity_O1_BigO"; -const char *rms_o_1_test_name = "BM_Complexity_O1_RMS"; -const char *enum_big_o_1 = "\\([0-9]+\\)"; -// FIXME: Tolerate both '(1)' and 'lgN' as output when the complexity is auto -// deduced. -// See https://github.com/google/benchmark/issues/272 -const char *auto_big_o_1 = "(\\([0-9]+\\))|(lgN)"; -const char *lambda_big_o_1 = "f\\(N\\)"; - -// Add enum tests -ADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name, - enum_big_o_1); - -// Add auto enum tests -ADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name, - auto_big_o_1); - -// Add lambda tests -ADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name, - lambda_big_o_1); - -// ========================================================================= // -// --------------------------- Testing BigO O(N) --------------------------- // -// ========================================================================= // - -std::vector ConstructRandomVector(int64_t size) { - std::vector v; - v.reserve(static_cast(size)); - for (int i = 0; i < size; ++i) { - v.push_back(static_cast(std::rand() % size)); - } - return v; -} - -void BM_Complexity_O_N(benchmark::State& state) { - auto v = ConstructRandomVector(state.range(0)); - // Test worst case scenario (item not in vector) - const int64_t item_not_in_vector = state.range(0) * 2; - for (auto _ : state) { - benchmark::DoNotOptimize(std::find(v.begin(), v.end(), item_not_in_vector)); - } - state.SetComplexityN(state.range(0)); -} -BENCHMARK(BM_Complexity_O_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity(benchmark::oN); -BENCHMARK(BM_Complexity_O_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity([](benchmark::IterationCount n) -> double { - return static_cast(n); - }); -BENCHMARK(BM_Complexity_O_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity(); - -const char *n_test_name = "BM_Complexity_O_N"; -const char *big_o_n_test_name = "BM_Complexity_O_N_BigO"; -const char *rms_o_n_test_name = "BM_Complexity_O_N_RMS"; -const char *enum_auto_big_o_n = "N"; -const char *lambda_big_o_n = "f\\(N\\)"; - -// Add enum tests -ADD_COMPLEXITY_CASES(n_test_name, big_o_n_test_name, rms_o_n_test_name, - enum_auto_big_o_n); - -// Add lambda tests -ADD_COMPLEXITY_CASES(n_test_name, big_o_n_test_name, rms_o_n_test_name, - lambda_big_o_n); - -// ========================================================================= // -// ------------------------- Testing BigO O(N*lgN) ------------------------- // -// ========================================================================= // - -static void BM_Complexity_O_N_log_N(benchmark::State& state) { - auto v = ConstructRandomVector(state.range(0)); - for (auto _ : state) { - std::sort(v.begin(), v.end()); - } - state.SetComplexityN(state.range(0)); -} -static const double kLog2E = 1.44269504088896340736; -BENCHMARK(BM_Complexity_O_N_log_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity(benchmark::oNLogN); -BENCHMARK(BM_Complexity_O_N_log_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity([](benchmark::IterationCount n) { - return kLog2E * n * log(static_cast(n)); - }); -BENCHMARK(BM_Complexity_O_N_log_N) - ->RangeMultiplier(2) - ->Range(1 << 10, 1 << 16) - ->Complexity(); - -const char *n_lg_n_test_name = "BM_Complexity_O_N_log_N"; -const char *big_o_n_lg_n_test_name = "BM_Complexity_O_N_log_N_BigO"; -const char *rms_o_n_lg_n_test_name = "BM_Complexity_O_N_log_N_RMS"; -const char *enum_auto_big_o_n_lg_n = "NlgN"; -const char *lambda_big_o_n_lg_n = "f\\(N\\)"; - -// Add enum tests -ADD_COMPLEXITY_CASES(n_lg_n_test_name, big_o_n_lg_n_test_name, - rms_o_n_lg_n_test_name, enum_auto_big_o_n_lg_n); - -// Add lambda tests -ADD_COMPLEXITY_CASES(n_lg_n_test_name, big_o_n_lg_n_test_name, - rms_o_n_lg_n_test_name, lambda_big_o_n_lg_n); - -// ========================================================================= // -// -------- Testing formatting of Complexity with captured args ------------ // -// ========================================================================= // - -void BM_ComplexityCaptureArgs(benchmark::State& state, int n) { - for (auto _ : state) { - } - state.SetComplexityN(n); -} - -BENCHMARK_CAPTURE(BM_ComplexityCaptureArgs, capture_test, 100) - ->Complexity(benchmark::oN) - ->Ranges({{1, 2}, {3, 4}}); - -const std::string complexity_capture_name = - "BM_ComplexityCaptureArgs/capture_test"; - -ADD_COMPLEXITY_CASES(complexity_capture_name, complexity_capture_name + "_BigO", - complexity_capture_name + "_RMS", "N"); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char *argv[]) { RunOutputTests(argc, argv); } diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/cxx03_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/cxx03_test.cc deleted file mode 100644 index c4c9a52273e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/cxx03_test.cc +++ /dev/null @@ -1,63 +0,0 @@ -#undef NDEBUG -#include -#include - -#include "benchmark/benchmark.h" - -#if __cplusplus >= 201103L -#error C++11 or greater detected. Should be C++03. -#endif - -#ifdef BENCHMARK_HAS_CXX11 -#error C++11 or greater detected by the library. BENCHMARK_HAS_CXX11 is defined. -#endif - -void BM_empty(benchmark::State& state) { - while (state.KeepRunning()) { - volatile benchmark::IterationCount x = state.iterations(); - ((void)x); - } -} -BENCHMARK(BM_empty); - -// The new C++11 interface for args/ranges requires initializer list support. -// Therefore we provide the old interface to support C++03. -void BM_old_arg_range_interface(benchmark::State& state) { - assert((state.range(0) == 1 && state.range(1) == 2) || - (state.range(0) == 5 && state.range(1) == 6)); - while (state.KeepRunning()) { - } -} -BENCHMARK(BM_old_arg_range_interface)->ArgPair(1, 2)->RangePair(5, 5, 6, 6); - -template -void BM_template2(benchmark::State& state) { - BM_empty(state); -} -BENCHMARK_TEMPLATE2(BM_template2, int, long); - -template -void BM_template1(benchmark::State& state) { - BM_empty(state); -} -BENCHMARK_TEMPLATE(BM_template1, long); -BENCHMARK_TEMPLATE1(BM_template1, int); - -template -struct BM_Fixture : public ::benchmark::Fixture { -}; - -BENCHMARK_TEMPLATE_F(BM_Fixture, BM_template1, long)(benchmark::State& state) { - BM_empty(state); -} -BENCHMARK_TEMPLATE1_F(BM_Fixture, BM_template2, int)(benchmark::State& state) { - BM_empty(state); -} - -void BM_counters(benchmark::State& state) { - BM_empty(state); - state.counters["Foo"] = 2; -} -BENCHMARK(BM_counters); - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/diagnostics_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/diagnostics_test.cc deleted file mode 100644 index dd64a336553..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/diagnostics_test.cc +++ /dev/null @@ -1,80 +0,0 @@ -// Testing: -// State::PauseTiming() -// State::ResumeTiming() -// Test that CHECK's within these function diagnose when they are called -// outside of the KeepRunning() loop. -// -// NOTE: Users should NOT include or use src/check.h. This is only done in -// order to test library internals. - -#include -#include - -#include "../src/check.h" -#include "benchmark/benchmark.h" - -#if defined(__GNUC__) && !defined(__EXCEPTIONS) -#define TEST_HAS_NO_EXCEPTIONS -#endif - -void TestHandler() { -#ifndef TEST_HAS_NO_EXCEPTIONS - throw std::logic_error(""); -#else - std::abort(); -#endif -} - -void try_invalid_pause_resume(benchmark::State& state) { -#if !defined(TEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS) && !defined(TEST_HAS_NO_EXCEPTIONS) - try { - state.PauseTiming(); - std::abort(); - } catch (std::logic_error const&) { - } - try { - state.ResumeTiming(); - std::abort(); - } catch (std::logic_error const&) { - } -#else - (void)state; // avoid unused warning -#endif -} - -void BM_diagnostic_test(benchmark::State& state) { - static bool called_once = false; - - if (called_once == false) try_invalid_pause_resume(state); - - for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); - } - - if (called_once == false) try_invalid_pause_resume(state); - - called_once = true; -} -BENCHMARK(BM_diagnostic_test); - - -void BM_diagnostic_test_keep_running(benchmark::State& state) { - static bool called_once = false; - - if (called_once == false) try_invalid_pause_resume(state); - - while(state.KeepRunning()) { - benchmark::DoNotOptimize(state.iterations()); - } - - if (called_once == false) try_invalid_pause_resume(state); - - called_once = true; -} -BENCHMARK(BM_diagnostic_test_keep_running); - -int main(int argc, char* argv[]) { - benchmark::internal::GetAbortHandler() = &TestHandler; - benchmark::Initialize(&argc, argv); - benchmark::RunSpecifiedBenchmarks(); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/display_aggregates_only_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/display_aggregates_only_test.cc deleted file mode 100644 index 3c36d3f03c1..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/display_aggregates_only_test.cc +++ /dev/null @@ -1,43 +0,0 @@ - -#undef NDEBUG -#include -#include - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// Ok this test is super ugly. We want to check what happens with the file -// reporter in the presence of DisplayAggregatesOnly(). -// We do not care about console output, the normal tests check that already. - -void BM_SummaryRepeat(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_SummaryRepeat)->Repetitions(3)->DisplayAggregatesOnly(); - -int main(int argc, char* argv[]) { - const std::string output = GetFileReporterOutput(argc, argv); - - if (SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3") != 6 || - SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3\"") != 3 || - SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_mean\"") != 1 || - SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_median\"") != - 1 || - SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\"") != - 1) { - std::cout << "Precondition mismatch. Expected to only find 6 " - "occurrences of \"BM_SummaryRepeat/repeats:3\" substring:\n" - "\"name\": \"BM_SummaryRepeat/repeats:3\", " - "\"name\": \"BM_SummaryRepeat/repeats:3\", " - "\"name\": \"BM_SummaryRepeat/repeats:3\", " - "\"name\": \"BM_SummaryRepeat/repeats:3_mean\", " - "\"name\": \"BM_SummaryRepeat/repeats:3_median\", " - "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\"\nThe entire " - "output:\n"; - std::cout << output; - return 1; - } - - return 0; -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/donotoptimize_assembly_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/donotoptimize_assembly_test.cc deleted file mode 100644 index d4b0bab70e7..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/donotoptimize_assembly_test.cc +++ /dev/null @@ -1,163 +0,0 @@ -#include - -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wreturn-type" -#endif - -extern "C" { - -extern int ExternInt; -extern int ExternInt2; -extern int ExternInt3; - -inline int Add42(int x) { return x + 42; } - -struct NotTriviallyCopyable { - NotTriviallyCopyable(); - explicit NotTriviallyCopyable(int x) : value(x) {} - NotTriviallyCopyable(NotTriviallyCopyable const&); - int value; -}; - -struct Large { - int value; - int data[2]; -}; - -} -// CHECK-LABEL: test_with_rvalue: -extern "C" void test_with_rvalue() { - benchmark::DoNotOptimize(Add42(0)); - // CHECK: movl $42, %eax - // CHECK: ret -} - -// CHECK-LABEL: test_with_large_rvalue: -extern "C" void test_with_large_rvalue() { - benchmark::DoNotOptimize(Large{ExternInt, {ExternInt, ExternInt}}); - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]] - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_non_trivial_rvalue: -extern "C" void test_with_non_trivial_rvalue() { - benchmark::DoNotOptimize(NotTriviallyCopyable(ExternInt)); - // CHECK: mov{{l|q}} ExternInt(%rip) - // CHECK: ret -} - -// CHECK-LABEL: test_with_lvalue: -extern "C" void test_with_lvalue() { - int x = 101; - benchmark::DoNotOptimize(x); - // CHECK-GNU: movl $101, %eax - // CHECK-CLANG: movl $101, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_large_lvalue: -extern "C" void test_with_large_lvalue() { - Large L{ExternInt, {ExternInt, ExternInt}}; - benchmark::DoNotOptimize(L); - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_non_trivial_lvalue: -extern "C" void test_with_non_trivial_lvalue() { - NotTriviallyCopyable NTC(ExternInt); - benchmark::DoNotOptimize(NTC); - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_const_lvalue: -extern "C" void test_with_const_lvalue() { - const int x = 123; - benchmark::DoNotOptimize(x); - // CHECK: movl $123, %eax - // CHECK: ret -} - -// CHECK-LABEL: test_with_large_const_lvalue: -extern "C" void test_with_large_const_lvalue() { - const Large L{ExternInt, {ExternInt, ExternInt}}; - benchmark::DoNotOptimize(L); - // CHECK: ExternInt(%rip) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]]) - // CHECK: ret -} - -// CHECK-LABEL: test_with_non_trivial_const_lvalue: -extern "C" void test_with_non_trivial_const_lvalue() { - const NotTriviallyCopyable Obj(ExternInt); - benchmark::DoNotOptimize(Obj); - // CHECK: mov{{q|l}} ExternInt(%rip) - // CHECK: ret -} - -// CHECK-LABEL: test_div_by_two: -extern "C" int test_div_by_two(int input) { - int divisor = 2; - benchmark::DoNotOptimize(divisor); - return input / divisor; - // CHECK: movl $2, [[DEST:.*]] - // CHECK: idivl [[DEST]] - // CHECK: ret -} - -// CHECK-LABEL: test_inc_integer: -extern "C" int test_inc_integer() { - int x = 0; - for (int i=0; i < 5; ++i) - benchmark::DoNotOptimize(++x); - // CHECK: movl $1, [[DEST:.*]] - // CHECK: {{(addl \$1,|incl)}} [[DEST]] - // CHECK: {{(addl \$1,|incl)}} [[DEST]] - // CHECK: {{(addl \$1,|incl)}} [[DEST]] - // CHECK: {{(addl \$1,|incl)}} [[DEST]] - // CHECK-CLANG: movl [[DEST]], %eax - // CHECK: ret - return x; -} - -// CHECK-LABEL: test_pointer_rvalue -extern "C" void test_pointer_rvalue() { - // CHECK: movl $42, [[DEST:.*]] - // CHECK: leaq [[DEST]], %rax - // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: ret - int x = 42; - benchmark::DoNotOptimize(&x); -} - -// CHECK-LABEL: test_pointer_const_lvalue: -extern "C" void test_pointer_const_lvalue() { - // CHECK: movl $42, [[DEST:.*]] - // CHECK: leaq [[DEST]], %rax - // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]]) - // CHECK: ret - int x = 42; - int * const xp = &x; - benchmark::DoNotOptimize(xp); -} - -// CHECK-LABEL: test_pointer_lvalue: -extern "C" void test_pointer_lvalue() { - // CHECK: movl $42, [[DEST:.*]] - // CHECK: leaq [[DEST]], %rax - // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z+]+]]) - // CHECK: ret - int x = 42; - int *xp = &x; - benchmark::DoNotOptimize(xp); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/donotoptimize_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/donotoptimize_test.cc deleted file mode 100644 index 2ce92d1c72b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/donotoptimize_test.cc +++ /dev/null @@ -1,52 +0,0 @@ -#include "benchmark/benchmark.h" - -#include - -namespace { -#if defined(__GNUC__) -std::uint64_t double_up(const std::uint64_t x) __attribute__((const)); -#endif -std::uint64_t double_up(const std::uint64_t x) { return x * 2; } -} - -// Using DoNotOptimize on types like BitRef seem to cause a lot of problems -// with the inline assembly on both GCC and Clang. -struct BitRef { - int index; - unsigned char &byte; - -public: - static BitRef Make() { - static unsigned char arr[2] = {}; - BitRef b(1, arr[0]); - return b; - } -private: - BitRef(int i, unsigned char& b) : index(i), byte(b) {} -}; - -int main(int, char*[]) { - // this test verifies compilation of DoNotOptimize() for some types - - char buffer8[8] = ""; - benchmark::DoNotOptimize(buffer8); - - char buffer20[20] = ""; - benchmark::DoNotOptimize(buffer20); - - char buffer1024[1024] = ""; - benchmark::DoNotOptimize(buffer1024); - benchmark::DoNotOptimize(&buffer1024[0]); - - int x = 123; - benchmark::DoNotOptimize(x); - benchmark::DoNotOptimize(&x); - benchmark::DoNotOptimize(x += 42); - - benchmark::DoNotOptimize(double_up(x)); - - // These tests are to e - benchmark::DoNotOptimize(BitRef::Make()); - BitRef lval = BitRef::Make(); - benchmark::DoNotOptimize(lval); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/filter_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/filter_test.cc deleted file mode 100644 index 0e27065c155..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/filter_test.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include "benchmark/benchmark.h" - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace { - -class TestReporter : public benchmark::ConsoleReporter { - public: - virtual bool ReportContext(const Context& context) { - return ConsoleReporter::ReportContext(context); - }; - - virtual void ReportRuns(const std::vector& report) { - ++count_; - ConsoleReporter::ReportRuns(report); - }; - - TestReporter() : count_(0) {} - - virtual ~TestReporter() {} - - size_t GetCount() const { return count_; } - - private: - mutable size_t count_; -}; - -} // end namespace - -static void NoPrefix(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(NoPrefix); - -static void BM_Foo(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_Foo); - -static void BM_Bar(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_Bar); - -static void BM_FooBar(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_FooBar); - -static void BM_FooBa(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_FooBa); - -int main(int argc, char **argv) { - bool list_only = false; - for (int i = 0; i < argc; ++i) - list_only |= std::string(argv[i]).find("--benchmark_list_tests") != - std::string::npos; - - benchmark::Initialize(&argc, argv); - - TestReporter test_reporter; - const size_t returned_count = - benchmark::RunSpecifiedBenchmarks(&test_reporter); - - if (argc == 2) { - // Make sure we ran all of the tests - std::stringstream ss(argv[1]); - size_t expected_return; - ss >> expected_return; - - if (returned_count != expected_return) { - std::cerr << "ERROR: Expected " << expected_return - << " tests to match the filter but returned_count = " - << returned_count << std::endl; - return -1; - } - - const size_t expected_reports = list_only ? 0 : expected_return; - const size_t reports_count = test_reporter.GetCount(); - if (reports_count != expected_reports) { - std::cerr << "ERROR: Expected " << expected_reports - << " tests to be run but reported_count = " << reports_count - << std::endl; - return -1; - } - } - - return 0; -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/fixture_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/fixture_test.cc deleted file mode 100644 index 1462b10f02f..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/fixture_test.cc +++ /dev/null @@ -1,49 +0,0 @@ - -#include "benchmark/benchmark.h" - -#include -#include - -class MyFixture : public ::benchmark::Fixture { - public: - void SetUp(const ::benchmark::State& state) { - if (state.thread_index == 0) { - assert(data.get() == nullptr); - data.reset(new int(42)); - } - } - - void TearDown(const ::benchmark::State& state) { - if (state.thread_index == 0) { - assert(data.get() != nullptr); - data.reset(); - } - } - - ~MyFixture() { assert(data == nullptr); } - - std::unique_ptr data; -}; - -BENCHMARK_F(MyFixture, Foo)(benchmark::State &st) { - assert(data.get() != nullptr); - assert(*data == 42); - for (auto _ : st) { - } -} - -BENCHMARK_DEFINE_F(MyFixture, Bar)(benchmark::State& st) { - if (st.thread_index == 0) { - assert(data.get() != nullptr); - assert(*data == 42); - } - for (auto _ : st) { - assert(data.get() != nullptr); - assert(*data == 42); - } - st.SetItemsProcessed(st.range(0)); -} -BENCHMARK_REGISTER_F(MyFixture, Bar)->Arg(42); -BENCHMARK_REGISTER_F(MyFixture, Bar)->Arg(42)->ThreadPerCpu(); - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/internal_threading_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/internal_threading_test.cc deleted file mode 100644 index 039d7c14a8c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/internal_threading_test.cc +++ /dev/null @@ -1,184 +0,0 @@ - -#undef NDEBUG - -#include -#include -#include "../src/timers.h" -#include "benchmark/benchmark.h" -#include "output_test.h" - -static const std::chrono::duration time_frame(50); -static const double time_frame_in_sec( - std::chrono::duration_cast>>( - time_frame) - .count()); - -void MyBusySpinwait() { - const auto start = benchmark::ChronoClockNow(); - - while (true) { - const auto now = benchmark::ChronoClockNow(); - const auto elapsed = now - start; - - if (std::chrono::duration(elapsed) >= - time_frame) - return; - } -} - -// ========================================================================= // -// --------------------------- TEST CASES BEGIN ---------------------------- // -// ========================================================================= // - -// ========================================================================= // -// BM_MainThread - -void BM_MainThread(benchmark::State& state) { - for (auto _ : state) { - MyBusySpinwait(); - state.SetIterationTime(time_frame_in_sec); - } - state.counters["invtime"] = - benchmark::Counter{1, benchmark::Counter::kIsRate}; -} - -BENCHMARK(BM_MainThread)->Iterations(1)->Threads(1); -BENCHMARK(BM_MainThread)->Iterations(1)->Threads(1)->UseRealTime(); -BENCHMARK(BM_MainThread)->Iterations(1)->Threads(1)->UseManualTime(); -BENCHMARK(BM_MainThread)->Iterations(1)->Threads(1)->MeasureProcessCPUTime(); -BENCHMARK(BM_MainThread) - ->Iterations(1) - ->Threads(1) - ->MeasureProcessCPUTime() - ->UseRealTime(); -BENCHMARK(BM_MainThread) - ->Iterations(1) - ->Threads(1) - ->MeasureProcessCPUTime() - ->UseManualTime(); - -BENCHMARK(BM_MainThread)->Iterations(1)->Threads(2); -BENCHMARK(BM_MainThread)->Iterations(1)->Threads(2)->UseRealTime(); -BENCHMARK(BM_MainThread)->Iterations(1)->Threads(2)->UseManualTime(); -BENCHMARK(BM_MainThread)->Iterations(1)->Threads(2)->MeasureProcessCPUTime(); -BENCHMARK(BM_MainThread) - ->Iterations(1) - ->Threads(2) - ->MeasureProcessCPUTime() - ->UseRealTime(); -BENCHMARK(BM_MainThread) - ->Iterations(1) - ->Threads(2) - ->MeasureProcessCPUTime() - ->UseManualTime(); - -// ========================================================================= // -// BM_WorkerThread - -void BM_WorkerThread(benchmark::State& state) { - for (auto _ : state) { - std::thread Worker(&MyBusySpinwait); - Worker.join(); - state.SetIterationTime(time_frame_in_sec); - } - state.counters["invtime"] = - benchmark::Counter{1, benchmark::Counter::kIsRate}; -} - -BENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(1); -BENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(1)->UseRealTime(); -BENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(1)->UseManualTime(); -BENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(1)->MeasureProcessCPUTime(); -BENCHMARK(BM_WorkerThread) - ->Iterations(1) - ->Threads(1) - ->MeasureProcessCPUTime() - ->UseRealTime(); -BENCHMARK(BM_WorkerThread) - ->Iterations(1) - ->Threads(1) - ->MeasureProcessCPUTime() - ->UseManualTime(); - -BENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(2); -BENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(2)->UseRealTime(); -BENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(2)->UseManualTime(); -BENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(2)->MeasureProcessCPUTime(); -BENCHMARK(BM_WorkerThread) - ->Iterations(1) - ->Threads(2) - ->MeasureProcessCPUTime() - ->UseRealTime(); -BENCHMARK(BM_WorkerThread) - ->Iterations(1) - ->Threads(2) - ->MeasureProcessCPUTime() - ->UseManualTime(); - -// ========================================================================= // -// BM_MainThreadAndWorkerThread - -void BM_MainThreadAndWorkerThread(benchmark::State& state) { - for (auto _ : state) { - std::thread Worker(&MyBusySpinwait); - MyBusySpinwait(); - Worker.join(); - state.SetIterationTime(time_frame_in_sec); - } - state.counters["invtime"] = - benchmark::Counter{1, benchmark::Counter::kIsRate}; -} - -BENCHMARK(BM_MainThreadAndWorkerThread)->Iterations(1)->Threads(1); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(1) - ->UseRealTime(); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(1) - ->UseManualTime(); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(1) - ->MeasureProcessCPUTime(); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(1) - ->MeasureProcessCPUTime() - ->UseRealTime(); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(1) - ->MeasureProcessCPUTime() - ->UseManualTime(); - -BENCHMARK(BM_MainThreadAndWorkerThread)->Iterations(1)->Threads(2); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(2) - ->UseRealTime(); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(2) - ->UseManualTime(); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(2) - ->MeasureProcessCPUTime(); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(2) - ->MeasureProcessCPUTime() - ->UseRealTime(); -BENCHMARK(BM_MainThreadAndWorkerThread) - ->Iterations(1) - ->Threads(2) - ->MeasureProcessCPUTime() - ->UseManualTime(); - -// ========================================================================= // -// ---------------------------- TEST CASES END ----------------------------- // -// ========================================================================= // - -int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/link_main_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/link_main_test.cc deleted file mode 100644 index 241ad5c3905..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/link_main_test.cc +++ /dev/null @@ -1,8 +0,0 @@ -#include "benchmark/benchmark.h" - -void BM_empty(benchmark::State& state) { - for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); - } -} -BENCHMARK(BM_empty); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/map_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/map_test.cc deleted file mode 100644 index dbf7982a368..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/map_test.cc +++ /dev/null @@ -1,57 +0,0 @@ -#include "benchmark/benchmark.h" - -#include -#include - -namespace { - -std::map ConstructRandomMap(int size) { - std::map m; - for (int i = 0; i < size; ++i) { - m.insert(std::make_pair(std::rand() % size, std::rand() % size)); - } - return m; -} - -} // namespace - -// Basic version. -static void BM_MapLookup(benchmark::State& state) { - const int size = static_cast(state.range(0)); - std::map m; - for (auto _ : state) { - state.PauseTiming(); - m = ConstructRandomMap(size); - state.ResumeTiming(); - for (int i = 0; i < size; ++i) { - benchmark::DoNotOptimize(m.find(std::rand() % size)); - } - } - state.SetItemsProcessed(state.iterations() * size); -} -BENCHMARK(BM_MapLookup)->Range(1 << 3, 1 << 12); - -// Using fixtures. -class MapFixture : public ::benchmark::Fixture { - public: - void SetUp(const ::benchmark::State& st) { - m = ConstructRandomMap(static_cast(st.range(0))); - } - - void TearDown(const ::benchmark::State&) { m.clear(); } - - std::map m; -}; - -BENCHMARK_DEFINE_F(MapFixture, Lookup)(benchmark::State& state) { - const int size = static_cast(state.range(0)); - for (auto _ : state) { - for (int i = 0; i < size; ++i) { - benchmark::DoNotOptimize(m.find(std::rand() % size)); - } - } - state.SetItemsProcessed(state.iterations() * size); -} -BENCHMARK_REGISTER_F(MapFixture, Lookup)->Range(1 << 3, 1 << 12); - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/memory_manager_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/memory_manager_test.cc deleted file mode 100644 index 90bed16cffd..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/memory_manager_test.cc +++ /dev/null @@ -1,44 +0,0 @@ -#include - -#include "../src/check.h" -#include "benchmark/benchmark.h" -#include "output_test.h" - -class TestMemoryManager : public benchmark::MemoryManager { - void Start() {} - void Stop(Result* result) { - result->num_allocs = 42; - result->max_bytes_used = 42000; - } -}; - -void BM_empty(benchmark::State& state) { - for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); - } -} -BENCHMARK(BM_empty); - -ADD_CASES(TC_ConsoleOut, {{"^BM_empty %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_empty\",$"}, - {"\"run_name\": \"BM_empty\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"allocs_per_iter\": %float,$", MR_Next}, - {"\"max_bytes_used\": 42000$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_empty\",%csv_report$"}}); - -int main(int argc, char* argv[]) { - std::unique_ptr mm(new TestMemoryManager()); - - benchmark::RegisterMemoryManager(mm.get()); - RunOutputTests(argc, argv); - benchmark::RegisterMemoryManager(nullptr); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/multiple_ranges_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/multiple_ranges_test.cc deleted file mode 100644 index b25f40eb520..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/multiple_ranges_test.cc +++ /dev/null @@ -1,96 +0,0 @@ -#include "benchmark/benchmark.h" - -#include -#include -#include -#include - -class MultipleRangesFixture : public ::benchmark::Fixture { - public: - MultipleRangesFixture() - : expectedValues({{1, 3, 5}, - {1, 3, 8}, - {1, 3, 15}, - {2, 3, 5}, - {2, 3, 8}, - {2, 3, 15}, - {1, 4, 5}, - {1, 4, 8}, - {1, 4, 15}, - {2, 4, 5}, - {2, 4, 8}, - {2, 4, 15}, - {1, 7, 5}, - {1, 7, 8}, - {1, 7, 15}, - {2, 7, 5}, - {2, 7, 8}, - {2, 7, 15}, - {7, 6, 3}}) {} - - void SetUp(const ::benchmark::State& state) { - std::vector ranges = {state.range(0), state.range(1), - state.range(2)}; - - assert(expectedValues.find(ranges) != expectedValues.end()); - - actualValues.insert(ranges); - } - - // NOTE: This is not TearDown as we want to check after _all_ runs are - // complete. - virtual ~MultipleRangesFixture() { - if (actualValues != expectedValues) { - std::cout << "EXPECTED\n"; - for (auto v : expectedValues) { - std::cout << "{"; - for (int64_t iv : v) { - std::cout << iv << ", "; - } - std::cout << "}\n"; - } - std::cout << "ACTUAL\n"; - for (auto v : actualValues) { - std::cout << "{"; - for (int64_t iv : v) { - std::cout << iv << ", "; - } - std::cout << "}\n"; - } - } - } - - std::set> expectedValues; - std::set> actualValues; -}; - -BENCHMARK_DEFINE_F(MultipleRangesFixture, Empty)(benchmark::State& state) { - for (auto _ : state) { - int64_t product = state.range(0) * state.range(1) * state.range(2); - for (int64_t x = 0; x < product; x++) { - benchmark::DoNotOptimize(x); - } - } -} - -BENCHMARK_REGISTER_F(MultipleRangesFixture, Empty) - ->RangeMultiplier(2) - ->Ranges({{1, 2}, {3, 7}, {5, 15}}) - ->Args({7, 6, 3}); - -void BM_CheckDefaultArgument(benchmark::State& state) { - // Test that the 'range()' without an argument is the same as 'range(0)'. - assert(state.range() == state.range(0)); - assert(state.range() != state.range(1)); - for (auto _ : state) { - } -} -BENCHMARK(BM_CheckDefaultArgument)->Ranges({{1, 5}, {6, 10}}); - -static void BM_MultipleRanges(benchmark::State& st) { - for (auto _ : st) { - } -} -BENCHMARK(BM_MultipleRanges)->Ranges({{5, 5}, {6, 6}}); - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/options_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/options_test.cc deleted file mode 100644 index 7bfc235465b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/options_test.cc +++ /dev/null @@ -1,75 +0,0 @@ -#include "benchmark/benchmark.h" -#include -#include - -#if defined(NDEBUG) -#undef NDEBUG -#endif -#include - -void BM_basic(benchmark::State& state) { - for (auto _ : state) { - } -} - -void BM_basic_slow(benchmark::State& state) { - std::chrono::milliseconds sleep_duration(state.range(0)); - for (auto _ : state) { - std::this_thread::sleep_for( - std::chrono::duration_cast(sleep_duration)); - } -} - -BENCHMARK(BM_basic); -BENCHMARK(BM_basic)->Arg(42); -BENCHMARK(BM_basic_slow)->Arg(10)->Unit(benchmark::kNanosecond); -BENCHMARK(BM_basic_slow)->Arg(100)->Unit(benchmark::kMicrosecond); -BENCHMARK(BM_basic_slow)->Arg(1000)->Unit(benchmark::kMillisecond); -BENCHMARK(BM_basic)->Range(1, 8); -BENCHMARK(BM_basic)->RangeMultiplier(2)->Range(1, 8); -BENCHMARK(BM_basic)->DenseRange(10, 15); -BENCHMARK(BM_basic)->Args({42, 42}); -BENCHMARK(BM_basic)->Ranges({{64, 512}, {64, 512}}); -BENCHMARK(BM_basic)->MinTime(0.7); -BENCHMARK(BM_basic)->UseRealTime(); -BENCHMARK(BM_basic)->ThreadRange(2, 4); -BENCHMARK(BM_basic)->ThreadPerCpu(); -BENCHMARK(BM_basic)->Repetitions(3); -BENCHMARK(BM_basic) - ->RangeMultiplier(std::numeric_limits::max()) - ->Range(std::numeric_limits::min(), - std::numeric_limits::max()); - -// Negative ranges -BENCHMARK(BM_basic)->Range(-64, -1); -BENCHMARK(BM_basic)->RangeMultiplier(4)->Range(-8, 8); -BENCHMARK(BM_basic)->DenseRange(-2, 2, 1); -BENCHMARK(BM_basic)->Ranges({{-64, 1}, {-8, -1}}); - -void CustomArgs(benchmark::internal::Benchmark* b) { - for (int i = 0; i < 10; ++i) { - b->Arg(i); - } -} - -BENCHMARK(BM_basic)->Apply(CustomArgs); - -void BM_explicit_iteration_count(benchmark::State& state) { - // Test that benchmarks specified with an explicit iteration count are - // only run once. - static bool invoked_before = false; - assert(!invoked_before); - invoked_before = true; - - // Test that the requested iteration count is respected. - assert(state.max_iterations == 42); - size_t actual_iterations = 0; - for (auto _ : state) - ++actual_iterations; - assert(state.iterations() == state.max_iterations); - assert(state.iterations() == 42); - -} -BENCHMARK(BM_explicit_iteration_count)->Iterations(42); - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/output_test.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/output_test.h deleted file mode 100644 index 9385761b214..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/output_test.h +++ /dev/null @@ -1,213 +0,0 @@ -#ifndef TEST_OUTPUT_TEST_H -#define TEST_OUTPUT_TEST_H - -#undef NDEBUG -#include -#include -#include -#include -#include -#include -#include - -#include "../src/re.h" -#include "benchmark/benchmark.h" - -#define CONCAT2(x, y) x##y -#define CONCAT(x, y) CONCAT2(x, y) - -#define ADD_CASES(...) int CONCAT(dummy, __LINE__) = ::AddCases(__VA_ARGS__) - -#define SET_SUBSTITUTIONS(...) \ - int CONCAT(dummy, __LINE__) = ::SetSubstitutions(__VA_ARGS__) - -enum MatchRules { - MR_Default, // Skip non-matching lines until a match is found. - MR_Next, // Match must occur on the next line. - MR_Not // No line between the current position and the next match matches - // the regex -}; - -struct TestCase { - TestCase(std::string re, int rule = MR_Default); - - std::string regex_str; - int match_rule; - std::string substituted_regex; - std::shared_ptr regex; -}; - -enum TestCaseID { - TC_ConsoleOut, - TC_ConsoleErr, - TC_JSONOut, - TC_JSONErr, - TC_CSVOut, - TC_CSVErr, - - TC_NumID // PRIVATE -}; - -// Add a list of test cases to be run against the output specified by -// 'ID' -int AddCases(TestCaseID ID, std::initializer_list il); - -// Add or set a list of substitutions to be performed on constructed regex's -// See 'output_test_helper.cc' for a list of default substitutions. -int SetSubstitutions( - std::initializer_list> il); - -// Run all output tests. -void RunOutputTests(int argc, char* argv[]); - -// Count the number of 'pat' substrings in the 'haystack' string. -int SubstrCnt(const std::string& haystack, const std::string& pat); - -// Run registered benchmarks with file reporter enabled, and return the content -// outputted by the file reporter. -std::string GetFileReporterOutput(int argc, char* argv[]); - -// ========================================================================= // -// ------------------------- Results checking ------------------------------ // -// ========================================================================= // - -// Call this macro to register a benchmark for checking its results. This -// should be all that's needed. It subscribes a function to check the (CSV) -// results of a benchmark. This is done only after verifying that the output -// strings are really as expected. -// bm_name_pattern: a name or a regex pattern which will be matched against -// all the benchmark names. Matching benchmarks -// will be the subject of a call to checker_function -// checker_function: should be of type ResultsCheckFn (see below) -#define CHECK_BENCHMARK_RESULTS(bm_name_pattern, checker_function) \ - size_t CONCAT(dummy, __LINE__) = AddChecker(bm_name_pattern, checker_function) - -struct Results; -typedef std::function ResultsCheckFn; - -size_t AddChecker(const char* bm_name_pattern, ResultsCheckFn fn); - -// Class holding the results of a benchmark. -// It is passed in calls to checker functions. -struct Results { - // the benchmark name - std::string name; - // the benchmark fields - std::map values; - - Results(const std::string& n) : name(n) {} - - int NumThreads() const; - - double NumIterations() const; - - typedef enum { kCpuTime, kRealTime } BenchmarkTime; - - // get cpu_time or real_time in seconds - double GetTime(BenchmarkTime which) const; - - // get the real_time duration of the benchmark in seconds. - // it is better to use fuzzy float checks for this, as the float - // ASCII formatting is lossy. - double DurationRealTime() const { - return NumIterations() * GetTime(kRealTime); - } - // get the cpu_time duration of the benchmark in seconds - double DurationCPUTime() const { - return NumIterations() * GetTime(kCpuTime); - } - - // get the string for a result by name, or nullptr if the name - // is not found - const std::string* Get(const char* entry_name) const { - auto it = values.find(entry_name); - if (it == values.end()) return nullptr; - return &it->second; - } - - // get a result by name, parsed as a specific type. - // NOTE: for counters, use GetCounterAs instead. - template - T GetAs(const char* entry_name) const; - - // counters are written as doubles, so they have to be read first - // as a double, and only then converted to the asked type. - template - T GetCounterAs(const char* entry_name) const { - double dval = GetAs(entry_name); - T tval = static_cast(dval); - return tval; - } -}; - -template -T Results::GetAs(const char* entry_name) const { - auto* sv = Get(entry_name); - CHECK(sv != nullptr && !sv->empty()); - std::stringstream ss; - ss << *sv; - T out; - ss >> out; - CHECK(!ss.fail()); - return out; -} - -//---------------------------------- -// Macros to help in result checking. Do not use them with arguments causing -// side-effects. - -// clang-format off - -#define _CHECK_RESULT_VALUE(entry, getfn, var_type, var_name, relationship, value) \ - CONCAT(CHECK_, relationship) \ - (entry.getfn< var_type >(var_name), (value)) << "\n" \ - << __FILE__ << ":" << __LINE__ << ": " << (entry).name << ":\n" \ - << __FILE__ << ":" << __LINE__ << ": " \ - << "expected (" << #var_type << ")" << (var_name) \ - << "=" << (entry).getfn< var_type >(var_name) \ - << " to be " #relationship " to " << (value) << "\n" - -// check with tolerance. eps_factor is the tolerance window, which is -// interpreted relative to value (eg, 0.1 means 10% of value). -#define _CHECK_FLOAT_RESULT_VALUE(entry, getfn, var_type, var_name, relationship, value, eps_factor) \ - CONCAT(CHECK_FLOAT_, relationship) \ - (entry.getfn< var_type >(var_name), (value), (eps_factor) * (value)) << "\n" \ - << __FILE__ << ":" << __LINE__ << ": " << (entry).name << ":\n" \ - << __FILE__ << ":" << __LINE__ << ": " \ - << "expected (" << #var_type << ")" << (var_name) \ - << "=" << (entry).getfn< var_type >(var_name) \ - << " to be " #relationship " to " << (value) << "\n" \ - << __FILE__ << ":" << __LINE__ << ": " \ - << "with tolerance of " << (eps_factor) * (value) \ - << " (" << (eps_factor)*100. << "%), " \ - << "but delta was " << ((entry).getfn< var_type >(var_name) - (value)) \ - << " (" << (((entry).getfn< var_type >(var_name) - (value)) \ - / \ - ((value) > 1.e-5 || value < -1.e-5 ? value : 1.e-5)*100.) \ - << "%)" - -#define CHECK_RESULT_VALUE(entry, var_type, var_name, relationship, value) \ - _CHECK_RESULT_VALUE(entry, GetAs, var_type, var_name, relationship, value) - -#define CHECK_COUNTER_VALUE(entry, var_type, var_name, relationship, value) \ - _CHECK_RESULT_VALUE(entry, GetCounterAs, var_type, var_name, relationship, value) - -#define CHECK_FLOAT_RESULT_VALUE(entry, var_name, relationship, value, eps_factor) \ - _CHECK_FLOAT_RESULT_VALUE(entry, GetAs, double, var_name, relationship, value, eps_factor) - -#define CHECK_FLOAT_COUNTER_VALUE(entry, var_name, relationship, value, eps_factor) \ - _CHECK_FLOAT_RESULT_VALUE(entry, GetCounterAs, double, var_name, relationship, value, eps_factor) - -// clang-format on - -// ========================================================================= // -// --------------------------- Misc Utilities ------------------------------ // -// ========================================================================= // - -namespace { - -const char* const dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"; - -} // end namespace - -#endif // TEST_OUTPUT_TEST_H diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/output_test_helper.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/output_test_helper.cc deleted file mode 100644 index 5dc951d2bca..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/output_test_helper.cc +++ /dev/null @@ -1,505 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../src/benchmark_api_internal.h" -#include "../src/check.h" // NOTE: check.h is for internal use only! -#include "../src/re.h" // NOTE: re.h is for internal use only -#include "output_test.h" - -// ========================================================================= // -// ------------------------------ Internals -------------------------------- // -// ========================================================================= // -namespace internal { -namespace { - -using TestCaseList = std::vector; - -// Use a vector because the order elements are added matters during iteration. -// std::map/unordered_map don't guarantee that. -// For example: -// SetSubstitutions({{"%HelloWorld", "Hello"}, {"%Hello", "Hi"}}); -// Substitute("%HelloWorld") // Always expands to Hello. -using SubMap = std::vector>; - -TestCaseList& GetTestCaseList(TestCaseID ID) { - // Uses function-local statics to ensure initialization occurs - // before first use. - static TestCaseList lists[TC_NumID]; - return lists[ID]; -} - -SubMap& GetSubstitutions() { - // Don't use 'dec_re' from header because it may not yet be initialized. - // clang-format off - static std::string safe_dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"; - static std::string time_re = "([0-9]+[.])?[0-9]+"; - static SubMap map = { - {"%float", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"}, - // human-readable float - {"%hrfloat", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?[kMGTPEZYmunpfazy]?"}, - {"%int", "[ ]*[0-9]+"}, - {" %s ", "[ ]+"}, - {"%time", "[ ]*" + time_re + "[ ]+ns"}, - {"%console_report", "[ ]*" + time_re + "[ ]+ns [ ]*" + time_re + "[ ]+ns [ ]*[0-9]+"}, - {"%console_time_only_report", "[ ]*" + time_re + "[ ]+ns [ ]*" + time_re + "[ ]+ns"}, - {"%console_us_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us [ ]*[0-9]+"}, - {"%console_us_time_only_report", "[ ]*" + time_re + "[ ]+us [ ]*" + time_re + "[ ]+us"}, - {"%csv_header", - "name,iterations,real_time,cpu_time,time_unit,bytes_per_second," - "items_per_second,label,error_occurred,error_message"}, - {"%csv_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,,,"}, - {"%csv_us_report", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",us,,,,,"}, - {"%csv_bytes_report", - "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re + ",,,,"}, - {"%csv_items_report", - "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,," + safe_dec_re + ",,,"}, - {"%csv_bytes_items_report", - "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns," + safe_dec_re + - "," + safe_dec_re + ",,,"}, - {"%csv_label_report_begin", "[0-9]+," + safe_dec_re + "," + safe_dec_re + ",ns,,,"}, - {"%csv_label_report_end", ",,"}}; - // clang-format on - return map; -} - -std::string PerformSubstitutions(std::string source) { - SubMap const& subs = GetSubstitutions(); - using SizeT = std::string::size_type; - for (auto const& KV : subs) { - SizeT pos; - SizeT next_start = 0; - while ((pos = source.find(KV.first, next_start)) != std::string::npos) { - next_start = pos + KV.second.size(); - source.replace(pos, KV.first.size(), KV.second); - } - } - return source; -} - -void CheckCase(std::stringstream& remaining_output, TestCase const& TC, - TestCaseList const& not_checks) { - std::string first_line; - bool on_first = true; - std::string line; - while (remaining_output.eof() == false) { - CHECK(remaining_output.good()); - std::getline(remaining_output, line); - if (on_first) { - first_line = line; - on_first = false; - } - for (const auto& NC : not_checks) { - CHECK(!NC.regex->Match(line)) - << "Unexpected match for line \"" << line << "\" for MR_Not regex \"" - << NC.regex_str << "\"" - << "\n actual regex string \"" << TC.substituted_regex << "\"" - << "\n started matching near: " << first_line; - } - if (TC.regex->Match(line)) return; - CHECK(TC.match_rule != MR_Next) - << "Expected line \"" << line << "\" to match regex \"" << TC.regex_str - << "\"" - << "\n actual regex string \"" << TC.substituted_regex << "\"" - << "\n started matching near: " << first_line; - } - CHECK(remaining_output.eof() == false) - << "End of output reached before match for regex \"" << TC.regex_str - << "\" was found" - << "\n actual regex string \"" << TC.substituted_regex << "\"" - << "\n started matching near: " << first_line; -} - -void CheckCases(TestCaseList const& checks, std::stringstream& output) { - std::vector not_checks; - for (size_t i = 0; i < checks.size(); ++i) { - const auto& TC = checks[i]; - if (TC.match_rule == MR_Not) { - not_checks.push_back(TC); - continue; - } - CheckCase(output, TC, not_checks); - not_checks.clear(); - } -} - -class TestReporter : public benchmark::BenchmarkReporter { - public: - TestReporter(std::vector reps) - : reporters_(reps) {} - - virtual bool ReportContext(const Context& context) { - bool last_ret = false; - bool first = true; - for (auto rep : reporters_) { - bool new_ret = rep->ReportContext(context); - CHECK(first || new_ret == last_ret) - << "Reports return different values for ReportContext"; - first = false; - last_ret = new_ret; - } - (void)first; - return last_ret; - } - - void ReportRuns(const std::vector& report) { - for (auto rep : reporters_) rep->ReportRuns(report); - } - void Finalize() { - for (auto rep : reporters_) rep->Finalize(); - } - - private: - std::vector reporters_; -}; -} // namespace - -} // end namespace internal - -// ========================================================================= // -// -------------------------- Results checking ----------------------------- // -// ========================================================================= // - -namespace internal { - -// Utility class to manage subscribers for checking benchmark results. -// It works by parsing the CSV output to read the results. -class ResultsChecker { - public: - struct PatternAndFn : public TestCase { // reusing TestCase for its regexes - PatternAndFn(const std::string& rx, ResultsCheckFn fn_) - : TestCase(rx), fn(fn_) {} - ResultsCheckFn fn; - }; - - std::vector check_patterns; - std::vector results; - std::vector field_names; - - void Add(const std::string& entry_pattern, ResultsCheckFn fn); - - void CheckResults(std::stringstream& output); - - private: - void SetHeader_(const std::string& csv_header); - void SetValues_(const std::string& entry_csv_line); - - std::vector SplitCsv_(const std::string& line); -}; - -// store the static ResultsChecker in a function to prevent initialization -// order problems -ResultsChecker& GetResultsChecker() { - static ResultsChecker rc; - return rc; -} - -// add a results checker for a benchmark -void ResultsChecker::Add(const std::string& entry_pattern, ResultsCheckFn fn) { - check_patterns.emplace_back(entry_pattern, fn); -} - -// check the results of all subscribed benchmarks -void ResultsChecker::CheckResults(std::stringstream& output) { - // first reset the stream to the start - { - auto start = std::stringstream::pos_type(0); - // clear before calling tellg() - output.clear(); - // seek to zero only when needed - if (output.tellg() > start) output.seekg(start); - // and just in case - output.clear(); - } - // now go over every line and publish it to the ResultsChecker - std::string line; - bool on_first = true; - while (output.eof() == false) { - CHECK(output.good()); - std::getline(output, line); - if (on_first) { - SetHeader_(line); // this is important - on_first = false; - continue; - } - SetValues_(line); - } - // finally we can call the subscribed check functions - for (const auto& p : check_patterns) { - VLOG(2) << "--------------------------------\n"; - VLOG(2) << "checking for benchmarks matching " << p.regex_str << "...\n"; - for (const auto& r : results) { - if (!p.regex->Match(r.name)) { - VLOG(2) << p.regex_str << " is not matched by " << r.name << "\n"; - continue; - } else { - VLOG(2) << p.regex_str << " is matched by " << r.name << "\n"; - } - VLOG(1) << "Checking results of " << r.name << ": ... \n"; - p.fn(r); - VLOG(1) << "Checking results of " << r.name << ": OK.\n"; - } - } -} - -// prepare for the names in this header -void ResultsChecker::SetHeader_(const std::string& csv_header) { - field_names = SplitCsv_(csv_header); -} - -// set the values for a benchmark -void ResultsChecker::SetValues_(const std::string& entry_csv_line) { - if (entry_csv_line.empty()) return; // some lines are empty - CHECK(!field_names.empty()); - auto vals = SplitCsv_(entry_csv_line); - CHECK_EQ(vals.size(), field_names.size()); - results.emplace_back(vals[0]); // vals[0] is the benchmark name - auto& entry = results.back(); - for (size_t i = 1, e = vals.size(); i < e; ++i) { - entry.values[field_names[i]] = vals[i]; - } -} - -// a quick'n'dirty csv splitter (eliminating quotes) -std::vector ResultsChecker::SplitCsv_(const std::string& line) { - std::vector out; - if (line.empty()) return out; - if (!field_names.empty()) out.reserve(field_names.size()); - size_t prev = 0, pos = line.find_first_of(','), curr = pos; - while (pos != line.npos) { - CHECK(curr > 0); - if (line[prev] == '"') ++prev; - if (line[curr - 1] == '"') --curr; - out.push_back(line.substr(prev, curr - prev)); - prev = pos + 1; - pos = line.find_first_of(',', pos + 1); - curr = pos; - } - curr = line.size(); - if (line[prev] == '"') ++prev; - if (line[curr - 1] == '"') --curr; - out.push_back(line.substr(prev, curr - prev)); - return out; -} - -} // end namespace internal - -size_t AddChecker(const char* bm_name, ResultsCheckFn fn) { - auto& rc = internal::GetResultsChecker(); - rc.Add(bm_name, fn); - return rc.results.size(); -} - -int Results::NumThreads() const { - auto pos = name.find("/threads:"); - if (pos == name.npos) return 1; - auto end = name.find('/', pos + 9); - std::stringstream ss; - ss << name.substr(pos + 9, end); - int num = 1; - ss >> num; - CHECK(!ss.fail()); - return num; -} - -double Results::NumIterations() const { - return GetAs("iterations"); -} - -double Results::GetTime(BenchmarkTime which) const { - CHECK(which == kCpuTime || which == kRealTime); - const char* which_str = which == kCpuTime ? "cpu_time" : "real_time"; - double val = GetAs(which_str); - auto unit = Get("time_unit"); - CHECK(unit); - if (*unit == "ns") { - return val * 1.e-9; - } else if (*unit == "us") { - return val * 1.e-6; - } else if (*unit == "ms") { - return val * 1.e-3; - } else if (*unit == "s") { - return val; - } else { - CHECK(1 == 0) << "unknown time unit: " << *unit; - return 0; - } -} - -// ========================================================================= // -// -------------------------- Public API Definitions------------------------ // -// ========================================================================= // - -TestCase::TestCase(std::string re, int rule) - : regex_str(std::move(re)), - match_rule(rule), - substituted_regex(internal::PerformSubstitutions(regex_str)), - regex(std::make_shared()) { - std::string err_str; - regex->Init(substituted_regex, &err_str); - CHECK(err_str.empty()) << "Could not construct regex \"" << substituted_regex - << "\"" - << "\n originally \"" << regex_str << "\"" - << "\n got error: " << err_str; -} - -int AddCases(TestCaseID ID, std::initializer_list il) { - auto& L = internal::GetTestCaseList(ID); - L.insert(L.end(), il); - return 0; -} - -int SetSubstitutions( - std::initializer_list> il) { - auto& subs = internal::GetSubstitutions(); - for (auto KV : il) { - bool exists = false; - KV.second = internal::PerformSubstitutions(KV.second); - for (auto& EKV : subs) { - if (EKV.first == KV.first) { - EKV.second = std::move(KV.second); - exists = true; - break; - } - } - if (!exists) subs.push_back(std::move(KV)); - } - return 0; -} - -void RunOutputTests(int argc, char* argv[]) { - using internal::GetTestCaseList; - benchmark::Initialize(&argc, argv); - auto options = benchmark::internal::GetOutputOptions(/*force_no_color*/ true); - benchmark::ConsoleReporter CR(options); - benchmark::JSONReporter JR; - benchmark::CSVReporter CSVR; - struct ReporterTest { - const char* name; - std::vector& output_cases; - std::vector& error_cases; - benchmark::BenchmarkReporter& reporter; - std::stringstream out_stream; - std::stringstream err_stream; - - ReporterTest(const char* n, std::vector& out_tc, - std::vector& err_tc, - benchmark::BenchmarkReporter& br) - : name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) { - reporter.SetOutputStream(&out_stream); - reporter.SetErrorStream(&err_stream); - } - } TestCases[] = { - {"ConsoleReporter", GetTestCaseList(TC_ConsoleOut), - GetTestCaseList(TC_ConsoleErr), CR}, - {"JSONReporter", GetTestCaseList(TC_JSONOut), GetTestCaseList(TC_JSONErr), - JR}, - {"CSVReporter", GetTestCaseList(TC_CSVOut), GetTestCaseList(TC_CSVErr), - CSVR}, - }; - - // Create the test reporter and run the benchmarks. - std::cout << "Running benchmarks...\n"; - internal::TestReporter test_rep({&CR, &JR, &CSVR}); - benchmark::RunSpecifiedBenchmarks(&test_rep); - - for (auto& rep_test : TestCases) { - std::string msg = std::string("\nTesting ") + rep_test.name + " Output\n"; - std::string banner(msg.size() - 1, '-'); - std::cout << banner << msg << banner << "\n"; - - std::cerr << rep_test.err_stream.str(); - std::cout << rep_test.out_stream.str(); - - internal::CheckCases(rep_test.error_cases, rep_test.err_stream); - internal::CheckCases(rep_test.output_cases, rep_test.out_stream); - - std::cout << "\n"; - } - - // now that we know the output is as expected, we can dispatch - // the checks to subscribees. - auto& csv = TestCases[2]; - // would use == but gcc spits a warning - CHECK(std::strcmp(csv.name, "CSVReporter") == 0); - internal::GetResultsChecker().CheckResults(csv.out_stream); -} - -int SubstrCnt(const std::string& haystack, const std::string& pat) { - if (pat.length() == 0) return 0; - int count = 0; - for (size_t offset = haystack.find(pat); offset != std::string::npos; - offset = haystack.find(pat, offset + pat.length())) - ++count; - return count; -} - -static char ToHex(int ch) { - return ch < 10 ? static_cast('0' + ch) - : static_cast('a' + (ch - 10)); -} - -static char RandomHexChar() { - static std::mt19937 rd{std::random_device{}()}; - static std::uniform_int_distribution mrand{0, 15}; - return ToHex(mrand(rd)); -} - -static std::string GetRandomFileName() { - std::string model = "test.%%%%%%"; - for (auto & ch : model) { - if (ch == '%') - ch = RandomHexChar(); - } - return model; -} - -static bool FileExists(std::string const& name) { - std::ifstream in(name.c_str()); - return in.good(); -} - -static std::string GetTempFileName() { - // This function attempts to avoid race conditions where two tests - // create the same file at the same time. However, it still introduces races - // similar to tmpnam. - int retries = 3; - while (--retries) { - std::string name = GetRandomFileName(); - if (!FileExists(name)) - return name; - } - std::cerr << "Failed to create unique temporary file name" << std::endl; - std::abort(); -} - -std::string GetFileReporterOutput(int argc, char* argv[]) { - std::vector new_argv(argv, argv + argc); - assert(static_cast(argc) == new_argv.size()); - - std::string tmp_file_name = GetTempFileName(); - std::cout << "Will be using this as the tmp file: " << tmp_file_name << '\n'; - - std::string tmp = "--benchmark_out="; - tmp += tmp_file_name; - new_argv.emplace_back(const_cast(tmp.c_str())); - - argc = int(new_argv.size()); - - benchmark::Initialize(&argc, new_argv.data()); - benchmark::RunSpecifiedBenchmarks(); - - // Read the output back from the file, and delete the file. - std::ifstream tmp_stream(tmp_file_name); - std::string output = std::string((std::istreambuf_iterator(tmp_stream)), - std::istreambuf_iterator()); - std::remove(tmp_file_name.c_str()); - - return output; -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/register_benchmark_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/register_benchmark_test.cc deleted file mode 100644 index 3ac5b21fb34..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/register_benchmark_test.cc +++ /dev/null @@ -1,184 +0,0 @@ - -#undef NDEBUG -#include -#include - -#include "../src/check.h" // NOTE: check.h is for internal use only! -#include "benchmark/benchmark.h" - -namespace { - -class TestReporter : public benchmark::ConsoleReporter { - public: - virtual void ReportRuns(const std::vector& report) { - all_runs_.insert(all_runs_.end(), begin(report), end(report)); - ConsoleReporter::ReportRuns(report); - } - - std::vector all_runs_; -}; - -struct TestCase { - std::string name; - const char* label; - // Note: not explicit as we rely on it being converted through ADD_CASES. - TestCase(const char* xname) : TestCase(xname, nullptr) {} - TestCase(const char* xname, const char* xlabel) - : name(xname), label(xlabel) {} - - typedef benchmark::BenchmarkReporter::Run Run; - - void CheckRun(Run const& run) const { - // clang-format off - CHECK(name == run.benchmark_name()) << "expected " << name << " got " - << run.benchmark_name(); - if (label) { - CHECK(run.report_label == label) << "expected " << label << " got " - << run.report_label; - } else { - CHECK(run.report_label == ""); - } - // clang-format on - } -}; - -std::vector ExpectedResults; - -int AddCases(std::initializer_list const& v) { - for (auto N : v) { - ExpectedResults.push_back(N); - } - return 0; -} - -#define CONCAT(x, y) CONCAT2(x, y) -#define CONCAT2(x, y) x##y -#define ADD_CASES(...) int CONCAT(dummy, __LINE__) = AddCases({__VA_ARGS__}) - -} // end namespace - -typedef benchmark::internal::Benchmark* ReturnVal; - -//----------------------------------------------------------------------------// -// Test RegisterBenchmark with no additional arguments -//----------------------------------------------------------------------------// -void BM_function(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_function); -ReturnVal dummy = benchmark::RegisterBenchmark( - "BM_function_manual_registration", BM_function); -ADD_CASES({"BM_function"}, {"BM_function_manual_registration"}); - -//----------------------------------------------------------------------------// -// Test RegisterBenchmark with additional arguments -// Note: GCC <= 4.8 do not support this form of RegisterBenchmark because they -// reject the variadic pack expansion of lambda captures. -//----------------------------------------------------------------------------// -#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK - -void BM_extra_args(benchmark::State& st, const char* label) { - for (auto _ : st) { - } - st.SetLabel(label); -} -int RegisterFromFunction() { - std::pair cases[] = { - {"test1", "One"}, {"test2", "Two"}, {"test3", "Three"}}; - for (auto const& c : cases) - benchmark::RegisterBenchmark(c.first, &BM_extra_args, c.second); - return 0; -} -int dummy2 = RegisterFromFunction(); -ADD_CASES({"test1", "One"}, {"test2", "Two"}, {"test3", "Three"}); - -#endif // BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK - -//----------------------------------------------------------------------------// -// Test RegisterBenchmark with different callable types -//----------------------------------------------------------------------------// - -struct CustomFixture { - void operator()(benchmark::State& st) { - for (auto _ : st) { - } - } -}; - -void TestRegistrationAtRuntime() { -#ifdef BENCHMARK_HAS_CXX11 - { - CustomFixture fx; - benchmark::RegisterBenchmark("custom_fixture", fx); - AddCases({"custom_fixture"}); - } -#endif -#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK - { - const char* x = "42"; - auto capturing_lam = [=](benchmark::State& st) { - for (auto _ : st) { - } - st.SetLabel(x); - }; - benchmark::RegisterBenchmark("lambda_benchmark", capturing_lam); - AddCases({{"lambda_benchmark", x}}); - } -#endif -} - -// Test that all benchmarks, registered at either during static init or runtime, -// are run and the results are passed to the reported. -void RunTestOne() { - TestRegistrationAtRuntime(); - - TestReporter test_reporter; - benchmark::RunSpecifiedBenchmarks(&test_reporter); - - typedef benchmark::BenchmarkReporter::Run Run; - auto EB = ExpectedResults.begin(); - - for (Run const& run : test_reporter.all_runs_) { - assert(EB != ExpectedResults.end()); - EB->CheckRun(run); - ++EB; - } - assert(EB == ExpectedResults.end()); -} - -// Test that ClearRegisteredBenchmarks() clears all previously registered -// benchmarks. -// Also test that new benchmarks can be registered and ran afterwards. -void RunTestTwo() { - assert(ExpectedResults.size() != 0 && - "must have at least one registered benchmark"); - ExpectedResults.clear(); - benchmark::ClearRegisteredBenchmarks(); - - TestReporter test_reporter; - size_t num_ran = benchmark::RunSpecifiedBenchmarks(&test_reporter); - assert(num_ran == 0); - assert(test_reporter.all_runs_.begin() == test_reporter.all_runs_.end()); - - TestRegistrationAtRuntime(); - num_ran = benchmark::RunSpecifiedBenchmarks(&test_reporter); - assert(num_ran == ExpectedResults.size()); - - typedef benchmark::BenchmarkReporter::Run Run; - auto EB = ExpectedResults.begin(); - - for (Run const& run : test_reporter.all_runs_) { - assert(EB != ExpectedResults.end()); - EB->CheckRun(run); - ++EB; - } - assert(EB == ExpectedResults.end()); -} - -int main(int argc, char* argv[]) { - benchmark::Initialize(&argc, argv); - - RunTestOne(); - RunTestTwo(); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/report_aggregates_only_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/report_aggregates_only_test.cc deleted file mode 100644 index 9646b9be534..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/report_aggregates_only_test.cc +++ /dev/null @@ -1,39 +0,0 @@ - -#undef NDEBUG -#include -#include - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// Ok this test is super ugly. We want to check what happens with the file -// reporter in the presence of ReportAggregatesOnly(). -// We do not care about console output, the normal tests check that already. - -void BM_SummaryRepeat(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_SummaryRepeat)->Repetitions(3)->ReportAggregatesOnly(); - -int main(int argc, char* argv[]) { - const std::string output = GetFileReporterOutput(argc, argv); - - if (SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3") != 3 || - SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_mean\"") != 1 || - SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_median\"") != - 1 || - SubstrCnt(output, "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\"") != - 1) { - std::cout << "Precondition mismatch. Expected to only find three " - "occurrences of \"BM_SummaryRepeat/repeats:3\" substring:\n" - "\"name\": \"BM_SummaryRepeat/repeats:3_mean\", " - "\"name\": \"BM_SummaryRepeat/repeats:3_median\", " - "\"name\": \"BM_SummaryRepeat/repeats:3_stddev\"\nThe entire " - "output:\n"; - std::cout << output; - return 1; - } - - return 0; -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/reporter_output_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/reporter_output_test.cc deleted file mode 100644 index c8090d4aca9..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/reporter_output_test.cc +++ /dev/null @@ -1,742 +0,0 @@ - -#undef NDEBUG -#include - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// ========================================================================= // -// ---------------------- Testing Prologue Output -------------------------- // -// ========================================================================= // - -ADD_CASES(TC_ConsoleOut, {{"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations$", MR_Next}, - {"^[-]+$", MR_Next}}); -static int AddContextCases() { - AddCases(TC_ConsoleErr, - { - {"%int[-/]%int[-/]%int %int:%int:%int$", MR_Default}, - {"Running .*/reporter_output_test(\\.exe)?$", MR_Next}, - {"Run on \\(%int X %float MHz CPU s?\\)", MR_Next}, - }); - AddCases(TC_JSONOut, - {{"^\\{", MR_Default}, - {"\"context\":", MR_Next}, - {"\"date\": \"", MR_Next}, - {"\"host_name\":", MR_Next}, - {"\"executable\": \".*(/|\\\\)reporter_output_test(\\.exe)?\",", - MR_Next}, - {"\"num_cpus\": %int,$", MR_Next}, - {"\"mhz_per_cpu\": %float,$", MR_Next}, - {"\"cpu_scaling_enabled\": ", MR_Next}, - {"\"caches\": \\[$", MR_Next}}); - auto const& Info = benchmark::CPUInfo::Get(); - auto const& Caches = Info.caches; - if (!Caches.empty()) { - AddCases(TC_ConsoleErr, {{"CPU Caches:$", MR_Next}}); - } - for (size_t I = 0; I < Caches.size(); ++I) { - std::string num_caches_str = - Caches[I].num_sharing != 0 ? " \\(x%int\\)$" : "$"; - AddCases( - TC_ConsoleErr, - {{"L%int (Data|Instruction|Unified) %intK" + num_caches_str, MR_Next}}); - AddCases(TC_JSONOut, {{"\\{$", MR_Next}, - {"\"type\": \"", MR_Next}, - {"\"level\": %int,$", MR_Next}, - {"\"size\": %int,$", MR_Next}, - {"\"num_sharing\": %int$", MR_Next}, - {"}[,]{0,1}$", MR_Next}}); - } - AddCases(TC_JSONOut, {{"],$"}}); - auto const& LoadAvg = Info.load_avg; - if (!LoadAvg.empty()) { - AddCases(TC_ConsoleErr, - {{"Load Average: (%float, ){0,2}%float$", MR_Next}}); - } - AddCases(TC_JSONOut, {{"\"load_avg\": \\[(%float,?){0,3}],$", MR_Next}}); - return 0; -} -int dummy_register = AddContextCases(); -ADD_CASES(TC_CSVOut, {{"%csv_header"}}); - -// ========================================================================= // -// ------------------------ Testing Basic Output --------------------------- // -// ========================================================================= // - -void BM_basic(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_basic); - -ADD_CASES(TC_ConsoleOut, {{"^BM_basic %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_basic\",$"}, - {"\"run_name\": \"BM_basic\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\"$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_basic\",%csv_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Bytes per Second Output ---------------- // -// ========================================================================= // - -void BM_bytes_per_second(benchmark::State& state) { - for (auto _ : state) { - } - state.SetBytesProcessed(1); -} -BENCHMARK(BM_bytes_per_second); - -ADD_CASES(TC_ConsoleOut, {{"^BM_bytes_per_second %console_report " - "bytes_per_second=%float[kM]{0,1}/s$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_bytes_per_second\",$"}, - {"\"run_name\": \"BM_bytes_per_second\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bytes_per_second\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_bytes_per_second\",%csv_bytes_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Items per Second Output ---------------- // -// ========================================================================= // - -void BM_items_per_second(benchmark::State& state) { - for (auto _ : state) { - } - state.SetItemsProcessed(1); -} -BENCHMARK(BM_items_per_second); - -ADD_CASES(TC_ConsoleOut, {{"^BM_items_per_second %console_report " - "items_per_second=%float[kM]{0,1}/s$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_items_per_second\",$"}, - {"\"run_name\": \"BM_items_per_second\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"items_per_second\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_items_per_second\",%csv_items_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Label Output --------------------------- // -// ========================================================================= // - -void BM_label(benchmark::State& state) { - for (auto _ : state) { - } - state.SetLabel("some label"); -} -BENCHMARK(BM_label); - -ADD_CASES(TC_ConsoleOut, {{"^BM_label %console_report some label$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_label\",$"}, - {"\"run_name\": \"BM_label\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"label\": \"some label\"$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_label\",%csv_label_report_begin\"some " - "label\"%csv_label_report_end$"}}); - -// ========================================================================= // -// ------------------------ Testing Error Output --------------------------- // -// ========================================================================= // - -void BM_error(benchmark::State& state) { - state.SkipWithError("message"); - for (auto _ : state) { - } -} -BENCHMARK(BM_error); -ADD_CASES(TC_ConsoleOut, {{"^BM_error[ ]+ERROR OCCURRED: 'message'$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_error\",$"}, - {"\"run_name\": \"BM_error\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"error_occurred\": true,$", MR_Next}, - {"\"error_message\": \"message\",$", MR_Next}}); - -ADD_CASES(TC_CSVOut, {{"^\"BM_error\",,,,,,,,true,\"message\"$"}}); - -// ========================================================================= // -// ------------------------ Testing No Arg Name Output ----------------------- -// // -// ========================================================================= // - -void BM_no_arg_name(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_no_arg_name)->Arg(3); -ADD_CASES(TC_ConsoleOut, {{"^BM_no_arg_name/3 %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_no_arg_name/3\",$"}, - {"\"run_name\": \"BM_no_arg_name/3\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_no_arg_name/3\",%csv_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Arg Name Output ----------------------- // -// ========================================================================= // - -void BM_arg_name(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_arg_name)->ArgName("first")->Arg(3); -ADD_CASES(TC_ConsoleOut, {{"^BM_arg_name/first:3 %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_arg_name/first:3\",$"}, - {"\"run_name\": \"BM_arg_name/first:3\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_arg_name/first:3\",%csv_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Arg Names Output ----------------------- // -// ========================================================================= // - -void BM_arg_names(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_arg_names)->Args({2, 5, 4})->ArgNames({"first", "", "third"}); -ADD_CASES(TC_ConsoleOut, - {{"^BM_arg_names/first:2/5/third:4 %console_report$"}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_arg_names/first:2/5/third:4\",$"}, - {"\"run_name\": \"BM_arg_names/first:2/5/third:4\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_arg_names/first:2/5/third:4\",%csv_report$"}}); - -// ========================================================================= // -// ------------------------ Testing Big Args Output ------------------------ // -// ========================================================================= // - -void BM_BigArgs(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_BigArgs)->RangeMultiplier(2)->Range(1U << 30U, 1U << 31U); -ADD_CASES(TC_ConsoleOut, {{"^BM_BigArgs/1073741824 %console_report$"}, - {"^BM_BigArgs/2147483648 %console_report$"}}); - -// ========================================================================= // -// ----------------------- Testing Complexity Output ----------------------- // -// ========================================================================= // - -void BM_Complexity_O1(benchmark::State& state) { - for (auto _ : state) { - } - state.SetComplexityN(state.range(0)); -} -BENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity(benchmark::o1); -SET_SUBSTITUTIONS({{"%bigOStr", "[ ]* %float \\([0-9]+\\)"}, - {"%RMS", "[ ]*[0-9]+ %"}}); -ADD_CASES(TC_ConsoleOut, {{"^BM_Complexity_O1_BigO %bigOStr %bigOStr[ ]*$"}, - {"^BM_Complexity_O1_RMS %RMS %RMS[ ]*$"}}); - -// ========================================================================= // -// ----------------------- Testing Aggregate Output ------------------------ // -// ========================================================================= // - -// Test that non-aggregate data is printed by default -void BM_Repeat(benchmark::State& state) { - for (auto _ : state) { - } -} -// need two repetitions min to be able to output any aggregate output -BENCHMARK(BM_Repeat)->Repetitions(2); -ADD_CASES(TC_ConsoleOut, - {{"^BM_Repeat/repeats:2 %console_report$"}, - {"^BM_Repeat/repeats:2 %console_report$"}, - {"^BM_Repeat/repeats:2_mean %console_time_only_report [ ]*2$"}, - {"^BM_Repeat/repeats:2_median %console_time_only_report [ ]*2$"}, - {"^BM_Repeat/repeats:2_stddev %console_time_only_report [ ]*2$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Repeat/repeats:2\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:2\"", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:2\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:2\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"repetition_index\": 1,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:2_mean\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:2\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"mean\",$", MR_Next}, - {"\"iterations\": 2,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:2_median\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:2\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"median\",$", MR_Next}, - {"\"iterations\": 2,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:2_stddev\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:2\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"stddev\",$", MR_Next}, - {"\"iterations\": 2,$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Repeat/repeats:2\",%csv_report$"}, - {"^\"BM_Repeat/repeats:2\",%csv_report$"}, - {"^\"BM_Repeat/repeats:2_mean\",%csv_report$"}, - {"^\"BM_Repeat/repeats:2_median\",%csv_report$"}, - {"^\"BM_Repeat/repeats:2_stddev\",%csv_report$"}}); -// but for two repetitions, mean and median is the same, so let's repeat.. -BENCHMARK(BM_Repeat)->Repetitions(3); -ADD_CASES(TC_ConsoleOut, - {{"^BM_Repeat/repeats:3 %console_report$"}, - {"^BM_Repeat/repeats:3 %console_report$"}, - {"^BM_Repeat/repeats:3 %console_report$"}, - {"^BM_Repeat/repeats:3_mean %console_time_only_report [ ]*3$"}, - {"^BM_Repeat/repeats:3_median %console_time_only_report [ ]*3$"}, - {"^BM_Repeat/repeats:3_stddev %console_time_only_report [ ]*3$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Repeat/repeats:3\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:3\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"repetition_index\": 1,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:3\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"repetition_index\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:3_mean\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"mean\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:3_median\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"median\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:3_stddev\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:3\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"stddev\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Repeat/repeats:3\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3_mean\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3_median\",%csv_report$"}, - {"^\"BM_Repeat/repeats:3_stddev\",%csv_report$"}}); -// median differs between even/odd number of repetitions, so just to be sure -BENCHMARK(BM_Repeat)->Repetitions(4); -ADD_CASES(TC_ConsoleOut, - {{"^BM_Repeat/repeats:4 %console_report$"}, - {"^BM_Repeat/repeats:4 %console_report$"}, - {"^BM_Repeat/repeats:4 %console_report$"}, - {"^BM_Repeat/repeats:4 %console_report$"}, - {"^BM_Repeat/repeats:4_mean %console_time_only_report [ ]*4$"}, - {"^BM_Repeat/repeats:4_median %console_time_only_report [ ]*4$"}, - {"^BM_Repeat/repeats:4_stddev %console_time_only_report [ ]*4$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Repeat/repeats:4\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 4,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:4\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 4,$", MR_Next}, - {"\"repetition_index\": 1,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:4\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 4,$", MR_Next}, - {"\"repetition_index\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:4\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 4,$", MR_Next}, - {"\"repetition_index\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:4_mean\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 4,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"mean\",$", MR_Next}, - {"\"iterations\": 4,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:4_median\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 4,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"median\",$", MR_Next}, - {"\"iterations\": 4,$", MR_Next}, - {"\"name\": \"BM_Repeat/repeats:4_stddev\",$"}, - {"\"run_name\": \"BM_Repeat/repeats:4\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 4,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"stddev\",$", MR_Next}, - {"\"iterations\": 4,$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Repeat/repeats:4\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4_mean\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4_median\",%csv_report$"}, - {"^\"BM_Repeat/repeats:4_stddev\",%csv_report$"}}); - -// Test that a non-repeated test still prints non-aggregate results even when -// only-aggregate reports have been requested -void BM_RepeatOnce(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_RepeatOnce)->Repetitions(1)->ReportAggregatesOnly(); -ADD_CASES(TC_ConsoleOut, {{"^BM_RepeatOnce/repeats:1 %console_report$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_RepeatOnce/repeats:1\",$"}, - {"\"run_name\": \"BM_RepeatOnce/repeats:1\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 1,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_RepeatOnce/repeats:1\",%csv_report$"}}); - -// Test that non-aggregate data is not reported -void BM_SummaryRepeat(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_SummaryRepeat)->Repetitions(3)->ReportAggregatesOnly(); -ADD_CASES( - TC_ConsoleOut, - {{".*BM_SummaryRepeat/repeats:3 ", MR_Not}, - {"^BM_SummaryRepeat/repeats:3_mean %console_time_only_report [ ]*3$"}, - {"^BM_SummaryRepeat/repeats:3_median %console_time_only_report [ ]*3$"}, - {"^BM_SummaryRepeat/repeats:3_stddev %console_time_only_report [ ]*3$"}}); -ADD_CASES(TC_JSONOut, - {{".*BM_SummaryRepeat/repeats:3 ", MR_Not}, - {"\"name\": \"BM_SummaryRepeat/repeats:3_mean\",$"}, - {"\"run_name\": \"BM_SummaryRepeat/repeats:3\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"mean\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"name\": \"BM_SummaryRepeat/repeats:3_median\",$"}, - {"\"run_name\": \"BM_SummaryRepeat/repeats:3\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"median\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"name\": \"BM_SummaryRepeat/repeats:3_stddev\",$"}, - {"\"run_name\": \"BM_SummaryRepeat/repeats:3\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"stddev\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{".*BM_SummaryRepeat/repeats:3 ", MR_Not}, - {"^\"BM_SummaryRepeat/repeats:3_mean\",%csv_report$"}, - {"^\"BM_SummaryRepeat/repeats:3_median\",%csv_report$"}, - {"^\"BM_SummaryRepeat/repeats:3_stddev\",%csv_report$"}}); - -// Test that non-aggregate data is not displayed. -// NOTE: this test is kinda bad. we are only testing the display output. -// But we don't check that the file output still contains everything... -void BM_SummaryDisplay(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_SummaryDisplay)->Repetitions(2)->DisplayAggregatesOnly(); -ADD_CASES( - TC_ConsoleOut, - {{".*BM_SummaryDisplay/repeats:2 ", MR_Not}, - {"^BM_SummaryDisplay/repeats:2_mean %console_time_only_report [ ]*2$"}, - {"^BM_SummaryDisplay/repeats:2_median %console_time_only_report [ ]*2$"}, - {"^BM_SummaryDisplay/repeats:2_stddev %console_time_only_report [ ]*2$"}}); -ADD_CASES(TC_JSONOut, - {{".*BM_SummaryDisplay/repeats:2 ", MR_Not}, - {"\"name\": \"BM_SummaryDisplay/repeats:2_mean\",$"}, - {"\"run_name\": \"BM_SummaryDisplay/repeats:2\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"mean\",$", MR_Next}, - {"\"iterations\": 2,$", MR_Next}, - {"\"name\": \"BM_SummaryDisplay/repeats:2_median\",$"}, - {"\"run_name\": \"BM_SummaryDisplay/repeats:2\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"median\",$", MR_Next}, - {"\"iterations\": 2,$", MR_Next}, - {"\"name\": \"BM_SummaryDisplay/repeats:2_stddev\",$"}, - {"\"run_name\": \"BM_SummaryDisplay/repeats:2\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"stddev\",$", MR_Next}, - {"\"iterations\": 2,$", MR_Next}}); -ADD_CASES(TC_CSVOut, - {{".*BM_SummaryDisplay/repeats:2 ", MR_Not}, - {"^\"BM_SummaryDisplay/repeats:2_mean\",%csv_report$"}, - {"^\"BM_SummaryDisplay/repeats:2_median\",%csv_report$"}, - {"^\"BM_SummaryDisplay/repeats:2_stddev\",%csv_report$"}}); - -// Test repeats with custom time unit. -void BM_RepeatTimeUnit(benchmark::State& state) { - for (auto _ : state) { - } -} -BENCHMARK(BM_RepeatTimeUnit) - ->Repetitions(3) - ->ReportAggregatesOnly() - ->Unit(benchmark::kMicrosecond); -ADD_CASES( - TC_ConsoleOut, - {{".*BM_RepeatTimeUnit/repeats:3 ", MR_Not}, - {"^BM_RepeatTimeUnit/repeats:3_mean %console_us_time_only_report [ ]*3$"}, - {"^BM_RepeatTimeUnit/repeats:3_median %console_us_time_only_report [ " - "]*3$"}, - {"^BM_RepeatTimeUnit/repeats:3_stddev %console_us_time_only_report [ " - "]*3$"}}); -ADD_CASES(TC_JSONOut, - {{".*BM_RepeatTimeUnit/repeats:3 ", MR_Not}, - {"\"name\": \"BM_RepeatTimeUnit/repeats:3_mean\",$"}, - {"\"run_name\": \"BM_RepeatTimeUnit/repeats:3\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"mean\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"time_unit\": \"us\",?$"}, - {"\"name\": \"BM_RepeatTimeUnit/repeats:3_median\",$"}, - {"\"run_name\": \"BM_RepeatTimeUnit/repeats:3\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"median\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"time_unit\": \"us\",?$"}, - {"\"name\": \"BM_RepeatTimeUnit/repeats:3_stddev\",$"}, - {"\"run_name\": \"BM_RepeatTimeUnit/repeats:3\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"stddev\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"time_unit\": \"us\",?$"}}); -ADD_CASES(TC_CSVOut, - {{".*BM_RepeatTimeUnit/repeats:3 ", MR_Not}, - {"^\"BM_RepeatTimeUnit/repeats:3_mean\",%csv_us_report$"}, - {"^\"BM_RepeatTimeUnit/repeats:3_median\",%csv_us_report$"}, - {"^\"BM_RepeatTimeUnit/repeats:3_stddev\",%csv_us_report$"}}); - -// ========================================================================= // -// -------------------- Testing user-provided statistics ------------------- // -// ========================================================================= // - -const auto UserStatistics = [](const std::vector& v) { - return v.back(); -}; -void BM_UserStats(benchmark::State& state) { - for (auto _ : state) { - state.SetIterationTime(150 / 10e8); - } -} -// clang-format off -BENCHMARK(BM_UserStats) - ->Repetitions(3) - ->Iterations(5) - ->UseManualTime() - ->ComputeStatistics("", UserStatistics); -// clang-format on - -// check that user-provided stats is calculated, and is after the default-ones -// empty string as name is intentional, it would sort before anything else -ADD_CASES(TC_ConsoleOut, {{"^BM_UserStats/iterations:5/repeats:3/manual_time [ " - "]* 150 ns %time [ ]*5$"}, - {"^BM_UserStats/iterations:5/repeats:3/manual_time [ " - "]* 150 ns %time [ ]*5$"}, - {"^BM_UserStats/iterations:5/repeats:3/manual_time [ " - "]* 150 ns %time [ ]*5$"}, - {"^BM_UserStats/iterations:5/repeats:3/" - "manual_time_mean [ ]* 150 ns %time [ ]*3$"}, - {"^BM_UserStats/iterations:5/repeats:3/" - "manual_time_median [ ]* 150 ns %time [ ]*3$"}, - {"^BM_UserStats/iterations:5/repeats:3/" - "manual_time_stddev [ ]* 0.000 ns %time [ ]*3$"}, - {"^BM_UserStats/iterations:5/repeats:3/manual_time_ " - "[ ]* 150 ns %time [ ]*3$"}}); -ADD_CASES( - TC_JSONOut, - {{"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$"}, - {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", - MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": 5,$", MR_Next}, - {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, - {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$"}, - {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", - MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"repetition_index\": 1,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": 5,$", MR_Next}, - {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, - {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$"}, - {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", - MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"repetition_index\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": 5,$", MR_Next}, - {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, - {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time_mean\",$"}, - {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", - MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"mean\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, - {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time_median\",$"}, - {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", - MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"median\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}, - {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time_stddev\",$"}, - {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", - MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"stddev\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"name\": \"BM_UserStats/iterations:5/repeats:3/manual_time_\",$"}, - {"\"run_name\": \"BM_UserStats/iterations:5/repeats:3/manual_time\",$", - MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 3,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"\",$", MR_Next}, - {"\"iterations\": 3,$", MR_Next}, - {"\"real_time\": 1\\.5(0)*e\\+(0)*2,$", MR_Next}}); -ADD_CASES( - TC_CSVOut, - {{"^\"BM_UserStats/iterations:5/repeats:3/manual_time\",%csv_report$"}, - {"^\"BM_UserStats/iterations:5/repeats:3/manual_time\",%csv_report$"}, - {"^\"BM_UserStats/iterations:5/repeats:3/manual_time\",%csv_report$"}, - {"^\"BM_UserStats/iterations:5/repeats:3/manual_time_mean\",%csv_report$"}, - {"^\"BM_UserStats/iterations:5/repeats:3/" - "manual_time_median\",%csv_report$"}, - {"^\"BM_UserStats/iterations:5/repeats:3/" - "manual_time_stddev\",%csv_report$"}, - {"^\"BM_UserStats/iterations:5/repeats:3/manual_time_\",%csv_report$"}}); - -// ========================================================================= // -// ------------------------- Testing StrEscape JSON ------------------------ // -// ========================================================================= // -#if 0 // enable when csv testing code correctly handles multi-line fields -void BM_JSON_Format(benchmark::State& state) { - state.SkipWithError("val\b\f\n\r\t\\\"with\"es,capes"); - for (auto _ : state) { - } -} -BENCHMARK(BM_JSON_Format); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_JSON_Format\",$"}, - {"\"run_name\": \"BM_JSON_Format\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"error_occurred\": true,$", MR_Next}, - {R"("error_message": "val\\b\\f\\n\\r\\t\\\\\\"with\\"es,capes",$)", MR_Next}}); -#endif -// ========================================================================= // -// -------------------------- Testing CsvEscape ---------------------------- // -// ========================================================================= // - -void BM_CSV_Format(benchmark::State& state) { - state.SkipWithError("\"freedom\""); - for (auto _ : state) { - } -} -BENCHMARK(BM_CSV_Format); -ADD_CASES(TC_CSVOut, {{"^\"BM_CSV_Format\",,,,,,,,true,\"\"\"freedom\"\"\"$"}}); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/skip_with_error_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/skip_with_error_test.cc deleted file mode 100644 index 06579772ff7..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/skip_with_error_test.cc +++ /dev/null @@ -1,189 +0,0 @@ - -#undef NDEBUG -#include -#include - -#include "../src/check.h" // NOTE: check.h is for internal use only! -#include "benchmark/benchmark.h" - -namespace { - -class TestReporter : public benchmark::ConsoleReporter { - public: - virtual bool ReportContext(const Context& context) { - return ConsoleReporter::ReportContext(context); - }; - - virtual void ReportRuns(const std::vector& report) { - all_runs_.insert(all_runs_.end(), begin(report), end(report)); - ConsoleReporter::ReportRuns(report); - } - - TestReporter() {} - virtual ~TestReporter() {} - - mutable std::vector all_runs_; -}; - -struct TestCase { - std::string name; - bool error_occurred; - std::string error_message; - - typedef benchmark::BenchmarkReporter::Run Run; - - void CheckRun(Run const& run) const { - CHECK(name == run.benchmark_name()) - << "expected " << name << " got " << run.benchmark_name(); - CHECK(error_occurred == run.error_occurred); - CHECK(error_message == run.error_message); - if (error_occurred) { - // CHECK(run.iterations == 0); - } else { - CHECK(run.iterations != 0); - } - } -}; - -std::vector ExpectedResults; - -int AddCases(const char* base_name, std::initializer_list const& v) { - for (auto TC : v) { - TC.name = base_name + TC.name; - ExpectedResults.push_back(std::move(TC)); - } - return 0; -} - -#define CONCAT(x, y) CONCAT2(x, y) -#define CONCAT2(x, y) x##y -#define ADD_CASES(...) int CONCAT(dummy, __LINE__) = AddCases(__VA_ARGS__) - -} // end namespace - -void BM_error_before_running(benchmark::State& state) { - state.SkipWithError("error message"); - while (state.KeepRunning()) { - assert(false); - } -} -BENCHMARK(BM_error_before_running); -ADD_CASES("BM_error_before_running", {{"", true, "error message"}}); - -void BM_error_before_running_batch(benchmark::State& state) { - state.SkipWithError("error message"); - while (state.KeepRunningBatch(17)) { - assert(false); - } -} -BENCHMARK(BM_error_before_running_batch); -ADD_CASES("BM_error_before_running_batch", {{"", true, "error message"}}); - -void BM_error_before_running_range_for(benchmark::State& state) { - state.SkipWithError("error message"); - for (auto _ : state) { - assert(false); - } -} -BENCHMARK(BM_error_before_running_range_for); -ADD_CASES("BM_error_before_running_range_for", {{"", true, "error message"}}); - -void BM_error_during_running(benchmark::State& state) { - int first_iter = true; - while (state.KeepRunning()) { - if (state.range(0) == 1 && state.thread_index <= (state.threads / 2)) { - assert(first_iter); - first_iter = false; - state.SkipWithError("error message"); - } else { - state.PauseTiming(); - state.ResumeTiming(); - } - } -} -BENCHMARK(BM_error_during_running)->Arg(1)->Arg(2)->ThreadRange(1, 8); -ADD_CASES("BM_error_during_running", {{"/1/threads:1", true, "error message"}, - {"/1/threads:2", true, "error message"}, - {"/1/threads:4", true, "error message"}, - {"/1/threads:8", true, "error message"}, - {"/2/threads:1", false, ""}, - {"/2/threads:2", false, ""}, - {"/2/threads:4", false, ""}, - {"/2/threads:8", false, ""}}); - -void BM_error_during_running_ranged_for(benchmark::State& state) { - assert(state.max_iterations > 3 && "test requires at least a few iterations"); - int first_iter = true; - // NOTE: Users should not write the for loop explicitly. - for (auto It = state.begin(), End = state.end(); It != End; ++It) { - if (state.range(0) == 1) { - assert(first_iter); - first_iter = false; - state.SkipWithError("error message"); - // Test the unfortunate but documented behavior that the ranged-for loop - // doesn't automatically terminate when SkipWithError is set. - assert(++It != End); - break; // Required behavior - } - } -} -BENCHMARK(BM_error_during_running_ranged_for)->Arg(1)->Arg(2)->Iterations(5); -ADD_CASES("BM_error_during_running_ranged_for", - {{"/1/iterations:5", true, "error message"}, - {"/2/iterations:5", false, ""}}); - -void BM_error_after_running(benchmark::State& state) { - for (auto _ : state) { - benchmark::DoNotOptimize(state.iterations()); - } - if (state.thread_index <= (state.threads / 2)) - state.SkipWithError("error message"); -} -BENCHMARK(BM_error_after_running)->ThreadRange(1, 8); -ADD_CASES("BM_error_after_running", {{"/threads:1", true, "error message"}, - {"/threads:2", true, "error message"}, - {"/threads:4", true, "error message"}, - {"/threads:8", true, "error message"}}); - -void BM_error_while_paused(benchmark::State& state) { - bool first_iter = true; - while (state.KeepRunning()) { - if (state.range(0) == 1 && state.thread_index <= (state.threads / 2)) { - assert(first_iter); - first_iter = false; - state.PauseTiming(); - state.SkipWithError("error message"); - } else { - state.PauseTiming(); - state.ResumeTiming(); - } - } -} -BENCHMARK(BM_error_while_paused)->Arg(1)->Arg(2)->ThreadRange(1, 8); -ADD_CASES("BM_error_while_paused", {{"/1/threads:1", true, "error message"}, - {"/1/threads:2", true, "error message"}, - {"/1/threads:4", true, "error message"}, - {"/1/threads:8", true, "error message"}, - {"/2/threads:1", false, ""}, - {"/2/threads:2", false, ""}, - {"/2/threads:4", false, ""}, - {"/2/threads:8", false, ""}}); - -int main(int argc, char* argv[]) { - benchmark::Initialize(&argc, argv); - - TestReporter test_reporter; - benchmark::RunSpecifiedBenchmarks(&test_reporter); - - typedef benchmark::BenchmarkReporter::Run Run; - auto EB = ExpectedResults.begin(); - - for (Run const& run : test_reporter.all_runs_) { - assert(EB != ExpectedResults.end()); - EB->CheckRun(run); - ++EB; - } - assert(EB == ExpectedResults.end()); - - return 0; -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/state_assembly_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/state_assembly_test.cc deleted file mode 100644 index 7ddbb3b2a92..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/state_assembly_test.cc +++ /dev/null @@ -1,68 +0,0 @@ -#include - -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wreturn-type" -#endif - -// clang-format off -extern "C" { - extern int ExternInt; - benchmark::State& GetState(); - void Fn(); -} -// clang-format on - -using benchmark::State; - -// CHECK-LABEL: test_for_auto_loop: -extern "C" int test_for_auto_loop() { - State& S = GetState(); - int x = 42; - // CHECK: [[CALL:call(q)*]] _ZN9benchmark5State16StartKeepRunningEv - // CHECK-NEXT: testq %rbx, %rbx - // CHECK-NEXT: je [[LOOP_END:.*]] - - for (auto _ : S) { - // CHECK: .L[[LOOP_HEAD:[a-zA-Z0-9_]+]]: - // CHECK-GNU-NEXT: subq $1, %rbx - // CHECK-CLANG-NEXT: {{(addq \$1, %rax|incq %rax|addq \$-1, %rbx)}} - // CHECK-NEXT: jne .L[[LOOP_HEAD]] - benchmark::DoNotOptimize(x); - } - // CHECK: [[LOOP_END]]: - // CHECK: [[CALL]] _ZN9benchmark5State17FinishKeepRunningEv - - // CHECK: movl $101, %eax - // CHECK: ret - return 101; -} - -// CHECK-LABEL: test_while_loop: -extern "C" int test_while_loop() { - State& S = GetState(); - int x = 42; - - // CHECK: j{{(e|mp)}} .L[[LOOP_HEADER:[a-zA-Z0-9_]+]] - // CHECK-NEXT: .L[[LOOP_BODY:[a-zA-Z0-9_]+]]: - while (S.KeepRunning()) { - // CHECK-GNU-NEXT: subq $1, %[[IREG:[a-z]+]] - // CHECK-CLANG-NEXT: {{(addq \$-1,|decq)}} %[[IREG:[a-z]+]] - // CHECK: movq %[[IREG]], [[DEST:.*]] - benchmark::DoNotOptimize(x); - } - // CHECK-DAG: movq [[DEST]], %[[IREG]] - // CHECK-DAG: testq %[[IREG]], %[[IREG]] - // CHECK-DAG: jne .L[[LOOP_BODY]] - // CHECK-DAG: .L[[LOOP_HEADER]]: - - // CHECK: cmpb $0 - // CHECK-NEXT: jne .L[[LOOP_END:[a-zA-Z0-9_]+]] - // CHECK: [[CALL:call(q)*]] _ZN9benchmark5State16StartKeepRunningEv - - // CHECK: .L[[LOOP_END]]: - // CHECK: [[CALL]] _ZN9benchmark5State17FinishKeepRunningEv - - // CHECK: movl $101, %eax - // CHECK: ret - return 101; -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/statistics_gtest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/statistics_gtest.cc deleted file mode 100644 index 99e314920c5..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/statistics_gtest.cc +++ /dev/null @@ -1,28 +0,0 @@ -//===---------------------------------------------------------------------===// -// statistics_test - Unit tests for src/statistics.cc -//===---------------------------------------------------------------------===// - -#include "../src/statistics.h" -#include "gtest/gtest.h" - -namespace { -TEST(StatisticsTest, Mean) { - EXPECT_DOUBLE_EQ(benchmark::StatisticsMean({42, 42, 42, 42}), 42.0); - EXPECT_DOUBLE_EQ(benchmark::StatisticsMean({1, 2, 3, 4}), 2.5); - EXPECT_DOUBLE_EQ(benchmark::StatisticsMean({1, 2, 5, 10, 10, 14}), 7.0); -} - -TEST(StatisticsTest, Median) { - EXPECT_DOUBLE_EQ(benchmark::StatisticsMedian({42, 42, 42, 42}), 42.0); - EXPECT_DOUBLE_EQ(benchmark::StatisticsMedian({1, 2, 3, 4}), 2.5); - EXPECT_DOUBLE_EQ(benchmark::StatisticsMedian({1, 2, 5, 10, 10}), 5.0); -} - -TEST(StatisticsTest, StdDev) { - EXPECT_DOUBLE_EQ(benchmark::StatisticsStdDev({101, 101, 101, 101}), 0.0); - EXPECT_DOUBLE_EQ(benchmark::StatisticsStdDev({1, 2, 3}), 1.0); - EXPECT_FLOAT_EQ(benchmark::StatisticsStdDev({1.5, 2.4, 3.3, 4.2, 5.1}), - 1.42302495); -} - -} // end namespace diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/string_util_gtest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/string_util_gtest.cc deleted file mode 100644 index 2c5d073f613..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/string_util_gtest.cc +++ /dev/null @@ -1,146 +0,0 @@ -//===---------------------------------------------------------------------===// -// statistics_test - Unit tests for src/statistics.cc -//===---------------------------------------------------------------------===// - -#include "../src/string_util.h" -#include "gtest/gtest.h" - -namespace { -TEST(StringUtilTest, stoul) { - { - size_t pos = 0; - EXPECT_EQ(0ul, benchmark::stoul("0", &pos)); - EXPECT_EQ(1ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(7ul, benchmark::stoul("7", &pos)); - EXPECT_EQ(1ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(135ul, benchmark::stoul("135", &pos)); - EXPECT_EQ(3ul, pos); - } -#if ULONG_MAX == 0xFFFFFFFFul - { - size_t pos = 0; - EXPECT_EQ(0xFFFFFFFFul, benchmark::stoul("4294967295", &pos)); - EXPECT_EQ(10ul, pos); - } -#elif ULONG_MAX == 0xFFFFFFFFFFFFFFFFul - { - size_t pos = 0; - EXPECT_EQ(0xFFFFFFFFFFFFFFFFul, benchmark::stoul("18446744073709551615", &pos)); - EXPECT_EQ(20ul, pos); - } -#endif - { - size_t pos = 0; - EXPECT_EQ(10ul, benchmark::stoul("1010", &pos, 2)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(520ul, benchmark::stoul("1010", &pos, 8)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1010ul, benchmark::stoul("1010", &pos, 10)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(4112ul, benchmark::stoul("1010", &pos, 16)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(0xBEEFul, benchmark::stoul("BEEF", &pos, 16)); - EXPECT_EQ(4ul, pos); - } - { - ASSERT_THROW(benchmark::stoul("this is a test"), std::invalid_argument); - } -} - -TEST(StringUtilTest, stoi) { - { - size_t pos = 0; - EXPECT_EQ(0, benchmark::stoi("0", &pos)); - EXPECT_EQ(1ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(-17, benchmark::stoi("-17", &pos)); - EXPECT_EQ(3ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1357, benchmark::stoi("1357", &pos)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(10, benchmark::stoi("1010", &pos, 2)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(520, benchmark::stoi("1010", &pos, 8)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1010, benchmark::stoi("1010", &pos, 10)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(4112, benchmark::stoi("1010", &pos, 16)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(0xBEEF, benchmark::stoi("BEEF", &pos, 16)); - EXPECT_EQ(4ul, pos); - } - { - ASSERT_THROW(benchmark::stoi("this is a test"), std::invalid_argument); - } -} - -TEST(StringUtilTest, stod) { - { - size_t pos = 0; - EXPECT_EQ(0.0, benchmark::stod("0", &pos)); - EXPECT_EQ(1ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(-84.0, benchmark::stod("-84", &pos)); - EXPECT_EQ(3ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1234.0, benchmark::stod("1234", &pos)); - EXPECT_EQ(4ul, pos); - } - { - size_t pos = 0; - EXPECT_EQ(1.5, benchmark::stod("1.5", &pos)); - EXPECT_EQ(3ul, pos); - } - { - size_t pos = 0; - /* Note: exactly representable as double */ - EXPECT_EQ(-1.25e+9, benchmark::stod("-1.25e+9", &pos)); - EXPECT_EQ(8ul, pos); - } - { - ASSERT_THROW(benchmark::stod("this is a test"), std::invalid_argument); - } -} - -} // end namespace diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/templated_fixture_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/templated_fixture_test.cc deleted file mode 100644 index fe9865cc776..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/templated_fixture_test.cc +++ /dev/null @@ -1,28 +0,0 @@ - -#include "benchmark/benchmark.h" - -#include -#include - -template -class MyFixture : public ::benchmark::Fixture { - public: - MyFixture() : data(0) {} - - T data; -}; - -BENCHMARK_TEMPLATE_F(MyFixture, Foo, int)(benchmark::State& st) { - for (auto _ : st) { - data += 1; - } -} - -BENCHMARK_TEMPLATE_DEFINE_F(MyFixture, Bar, double)(benchmark::State& st) { - for (auto _ : st) { - data += 1.0; - } -} -BENCHMARK_REGISTER_F(MyFixture, Bar); - -BENCHMARK_MAIN(); diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/user_counters_tabular_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/user_counters_tabular_test.cc deleted file mode 100644 index 099464ef993..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/user_counters_tabular_test.cc +++ /dev/null @@ -1,283 +0,0 @@ - -#undef NDEBUG - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// @todo: this checks the full output at once; the rule for -// CounterSet1 was failing because it was not matching "^[-]+$". -// @todo: check that the counters are vertically aligned. -ADD_CASES( - TC_ConsoleOut, - { - // keeping these lines long improves readability, so: - // clang-format off - {"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Bat %s Baz %s Foo %s Frob %s Lob$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_Counters_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Baz %s Foo$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations %s Bat %s Baz %s Foo$", MR_Next}, - {"^[-]+$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$", MR_Next}, - {"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$"}, - // clang-format on - }); -ADD_CASES(TC_CSVOut, {{"%csv_header," - "\"Bar\",\"Bat\",\"Baz\",\"Foo\",\"Frob\",\"Lob\""}}); - -// ========================================================================= // -// ------------------------- Tabular Counters Output ----------------------- // -// ========================================================================= // - -void BM_Counters_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {1, bm::Counter::kAvgThreads}}, - {"Bar", {2, bm::Counter::kAvgThreads}}, - {"Baz", {4, bm::Counter::kAvgThreads}}, - {"Bat", {8, bm::Counter::kAvgThreads}}, - {"Frob", {16, bm::Counter::kAvgThreads}}, - {"Lob", {32, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_Counters_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_Counters_Tabular/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Bat\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float,$", MR_Next}, - {"\"Frob\": %float,$", MR_Next}, - {"\"Lob\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_Tabular/threads:%int\",%csv_report," - "%float,%float,%float,%float,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckTabular(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 1); - CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 2); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 4); - CHECK_COUNTER_VALUE(e, int, "Bat", EQ, 8); - CHECK_COUNTER_VALUE(e, int, "Frob", EQ, 16); - CHECK_COUNTER_VALUE(e, int, "Lob", EQ, 32); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Tabular/threads:%int", &CheckTabular); - -// ========================================================================= // -// -------------------- Tabular+Rate Counters Output ----------------------- // -// ========================================================================= // - -void BM_CounterRates_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {1, bm::Counter::kAvgThreadsRate}}, - {"Bar", {2, bm::Counter::kAvgThreadsRate}}, - {"Baz", {4, bm::Counter::kAvgThreadsRate}}, - {"Bat", {8, bm::Counter::kAvgThreadsRate}}, - {"Frob", {16, bm::Counter::kAvgThreadsRate}}, - {"Lob", {32, bm::Counter::kAvgThreadsRate}}, - }); -} -BENCHMARK(BM_CounterRates_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_CounterRates_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_CounterRates_Tabular/threads:%int\",$", - MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Bat\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float,$", MR_Next}, - {"\"Frob\": %float,$", MR_Next}, - {"\"Lob\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterRates_Tabular/threads:%int\",%csv_report," - "%float,%float,%float,%float,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckTabularRate(Results const& e) { - double t = e.DurationCPUTime(); - CHECK_FLOAT_COUNTER_VALUE(e, "Foo", EQ, 1. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Bar", EQ, 2. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Baz", EQ, 4. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Bat", EQ, 8. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Frob", EQ, 16. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "Lob", EQ, 32. / t, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_CounterRates_Tabular/threads:%int", - &CheckTabularRate); - -// ========================================================================= // -// ------------------------- Tabular Counters Output ----------------------- // -// ========================================================================= // - -// set only some of the counters -void BM_CounterSet0_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {10, bm::Counter::kAvgThreads}}, - {"Bar", {20, bm::Counter::kAvgThreads}}, - {"Baz", {40, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_CounterSet0_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_CounterSet0_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_CounterSet0_Tabular/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet0_Tabular/threads:%int\",%csv_report," - "%float,,%float,%float,,"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSet0(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 10); - CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 20); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 40); -} -CHECK_BENCHMARK_RESULTS("BM_CounterSet0_Tabular", &CheckSet0); - -// again. -void BM_CounterSet1_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {15, bm::Counter::kAvgThreads}}, - {"Bar", {25, bm::Counter::kAvgThreads}}, - {"Baz", {45, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_CounterSet1_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_CounterSet1_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_CounterSet1_Tabular/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bar\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet1_Tabular/threads:%int\",%csv_report," - "%float,,%float,%float,,"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSet1(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 15); - CHECK_COUNTER_VALUE(e, int, "Bar", EQ, 25); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 45); -} -CHECK_BENCHMARK_RESULTS("BM_CounterSet1_Tabular/threads:%int", &CheckSet1); - -// ========================================================================= // -// ------------------------- Tabular Counters Output ----------------------- // -// ========================================================================= // - -// set only some of the counters, different set now. -void BM_CounterSet2_Tabular(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"Foo", {10, bm::Counter::kAvgThreads}}, - {"Bat", {30, bm::Counter::kAvgThreads}}, - {"Baz", {40, bm::Counter::kAvgThreads}}, - }); -} -BENCHMARK(BM_CounterSet2_Tabular)->ThreadRange(1, 16); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_CounterSet2_Tabular/threads:%int\",$"}, - {"\"run_name\": \"BM_CounterSet2_Tabular/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"Bat\": %float,$", MR_Next}, - {"\"Baz\": %float,$", MR_Next}, - {"\"Foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_CounterSet2_Tabular/threads:%int\",%csv_report," - ",%float,%float,%float,,"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSet2(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "Foo", EQ, 10); - CHECK_COUNTER_VALUE(e, int, "Bat", EQ, 30); - CHECK_COUNTER_VALUE(e, int, "Baz", EQ, 40); -} -CHECK_BENCHMARK_RESULTS("BM_CounterSet2_Tabular", &CheckSet2); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/user_counters_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/user_counters_test.cc deleted file mode 100644 index 0775bc01f75..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/user_counters_test.cc +++ /dev/null @@ -1,438 +0,0 @@ - -#undef NDEBUG - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// ========================================================================= // -// ---------------------- Testing Prologue Output -------------------------- // -// ========================================================================= // - -// clang-format off - -ADD_CASES(TC_ConsoleOut, - {{"^[-]+$", MR_Next}, - {"^Benchmark %s Time %s CPU %s Iterations UserCounters...$", MR_Next}, - {"^[-]+$", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"%csv_header,\"bar\",\"foo\""}}); - -// clang-format on - -// ========================================================================= // -// ------------------------- Simple Counters Output ------------------------ // -// ========================================================================= // - -void BM_Counters_Simple(benchmark::State& state) { - for (auto _ : state) { - } - state.counters["foo"] = 1; - state.counters["bar"] = 2 * (double)state.iterations(); -} -BENCHMARK(BM_Counters_Simple); -ADD_CASES(TC_ConsoleOut, - {{"^BM_Counters_Simple %console_report bar=%hrfloat foo=%hrfloat$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Simple\",$"}, - {"\"run_name\": \"BM_Counters_Simple\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_Simple\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckSimple(Results const& e) { - double its = e.NumIterations(); - CHECK_COUNTER_VALUE(e, int, "foo", EQ, 1); - // check that the value of bar is within 0.1% of the expected value - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 2. * its, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Simple", &CheckSimple); - -// ========================================================================= // -// --------------------- Counters+Items+Bytes/s Output --------------------- // -// ========================================================================= // - -namespace { -int num_calls1 = 0; -} -void BM_Counters_WithBytesAndItemsPSec(benchmark::State& state) { - for (auto _ : state) { - } - state.counters["foo"] = 1; - state.counters["bar"] = ++num_calls1; - state.SetBytesProcessed(364); - state.SetItemsProcessed(150); -} -BENCHMARK(BM_Counters_WithBytesAndItemsPSec); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_WithBytesAndItemsPSec %console_report " - "bar=%hrfloat bytes_per_second=%hrfloat/s " - "foo=%hrfloat items_per_second=%hrfloat/s$"}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_WithBytesAndItemsPSec\",$"}, - {"\"run_name\": \"BM_Counters_WithBytesAndItemsPSec\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"bytes_per_second\": %float,$", MR_Next}, - {"\"foo\": %float,$", MR_Next}, - {"\"items_per_second\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_WithBytesAndItemsPSec\"," - "%csv_bytes_items_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckBytesAndItemsPSec(Results const& e) { - double t = e.DurationCPUTime(); // this (and not real time) is the time used - CHECK_COUNTER_VALUE(e, int, "foo", EQ, 1); - CHECK_COUNTER_VALUE(e, int, "bar", EQ, num_calls1); - // check that the values are within 0.1% of the expected values - CHECK_FLOAT_RESULT_VALUE(e, "bytes_per_second", EQ, 364. / t, 0.001); - CHECK_FLOAT_RESULT_VALUE(e, "items_per_second", EQ, 150. / t, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_WithBytesAndItemsPSec", - &CheckBytesAndItemsPSec); - -// ========================================================================= // -// ------------------------- Rate Counters Output -------------------------- // -// ========================================================================= // - -void BM_Counters_Rate(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = bm::Counter{1, bm::Counter::kIsRate}; - state.counters["bar"] = bm::Counter{2, bm::Counter::kIsRate}; -} -BENCHMARK(BM_Counters_Rate); -ADD_CASES( - TC_ConsoleOut, - {{"^BM_Counters_Rate %console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); -ADD_CASES(TC_JSONOut, {{"\"name\": \"BM_Counters_Rate\",$"}, - {"\"run_name\": \"BM_Counters_Rate\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_Rate\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckRate(Results const& e) { - double t = e.DurationCPUTime(); // this (and not real time) is the time used - // check that the values are within 0.1% of the expected values - CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, 1. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 2. / t, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Rate", &CheckRate); - -// ========================================================================= // -// ------------------------- Thread Counters Output ------------------------ // -// ========================================================================= // - -void BM_Counters_Threads(benchmark::State& state) { - for (auto _ : state) { - } - state.counters["foo"] = 1; - state.counters["bar"] = 2; -} -BENCHMARK(BM_Counters_Threads)->ThreadRange(1, 8); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_Threads/threads:%int %console_report " - "bar=%hrfloat foo=%hrfloat$"}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_Threads/threads:%int\",$"}, - {"\"run_name\": \"BM_Counters_Threads/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES( - TC_CSVOut, - {{"^\"BM_Counters_Threads/threads:%int\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckThreads(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "foo", EQ, e.NumThreads()); - CHECK_COUNTER_VALUE(e, int, "bar", EQ, 2 * e.NumThreads()); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Threads/threads:%int", &CheckThreads); - -// ========================================================================= // -// ---------------------- ThreadAvg Counters Output ------------------------ // -// ========================================================================= // - -void BM_Counters_AvgThreads(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = bm::Counter{1, bm::Counter::kAvgThreads}; - state.counters["bar"] = bm::Counter{2, bm::Counter::kAvgThreads}; -} -BENCHMARK(BM_Counters_AvgThreads)->ThreadRange(1, 8); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_AvgThreads/threads:%int " - "%console_report bar=%hrfloat foo=%hrfloat$"}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_AvgThreads/threads:%int\",$"}, - {"\"run_name\": \"BM_Counters_AvgThreads/threads:%int\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES( - TC_CSVOut, - {{"^\"BM_Counters_AvgThreads/threads:%int\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckAvgThreads(Results const& e) { - CHECK_COUNTER_VALUE(e, int, "foo", EQ, 1); - CHECK_COUNTER_VALUE(e, int, "bar", EQ, 2); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_AvgThreads/threads:%int", - &CheckAvgThreads); - -// ========================================================================= // -// ---------------------- ThreadAvg Counters Output ------------------------ // -// ========================================================================= // - -void BM_Counters_AvgThreadsRate(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = bm::Counter{1, bm::Counter::kAvgThreadsRate}; - state.counters["bar"] = bm::Counter{2, bm::Counter::kAvgThreadsRate}; -} -BENCHMARK(BM_Counters_AvgThreadsRate)->ThreadRange(1, 8); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_AvgThreadsRate/threads:%int " - "%console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_AvgThreadsRate/threads:%int\",$"}, - {"\"run_name\": \"BM_Counters_AvgThreadsRate/threads:%int\",$", - MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_AvgThreadsRate/" - "threads:%int\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckAvgThreadsRate(Results const& e) { - CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, 1. / e.DurationCPUTime(), 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 2. / e.DurationCPUTime(), 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_AvgThreadsRate/threads:%int", - &CheckAvgThreadsRate); - -// ========================================================================= // -// ------------------- IterationInvariant Counters Output ------------------ // -// ========================================================================= // - -void BM_Counters_IterationInvariant(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = bm::Counter{1, bm::Counter::kIsIterationInvariant}; - state.counters["bar"] = bm::Counter{2, bm::Counter::kIsIterationInvariant}; -} -BENCHMARK(BM_Counters_IterationInvariant); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_IterationInvariant %console_report " - "bar=%hrfloat foo=%hrfloat$"}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_IterationInvariant\",$"}, - {"\"run_name\": \"BM_Counters_IterationInvariant\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, - {{"^\"BM_Counters_IterationInvariant\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckIterationInvariant(Results const& e) { - double its = e.NumIterations(); - // check that the values are within 0.1% of the expected value - CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, its, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 2. * its, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_IterationInvariant", - &CheckIterationInvariant); - -// ========================================================================= // -// ----------------- IterationInvariantRate Counters Output ---------------- // -// ========================================================================= // - -void BM_Counters_kIsIterationInvariantRate(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = - bm::Counter{1, bm::Counter::kIsIterationInvariantRate}; - state.counters["bar"] = - bm::Counter{2, bm::Counter::kIsRate | bm::Counter::kIsIterationInvariant}; -} -BENCHMARK(BM_Counters_kIsIterationInvariantRate); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_kIsIterationInvariantRate " - "%console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_kIsIterationInvariantRate\",$"}, - {"\"run_name\": \"BM_Counters_kIsIterationInvariantRate\",$", - MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_kIsIterationInvariantRate\",%csv_report," - "%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckIsIterationInvariantRate(Results const& e) { - double its = e.NumIterations(); - double t = e.DurationCPUTime(); // this (and not real time) is the time used - // check that the values are within 0.1% of the expected values - CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, its * 1. / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, its * 2. / t, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_kIsIterationInvariantRate", - &CheckIsIterationInvariantRate); - -// ========================================================================= // -// ------------------- AvgIterations Counters Output ------------------ // -// ========================================================================= // - -void BM_Counters_AvgIterations(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = bm::Counter{1, bm::Counter::kAvgIterations}; - state.counters["bar"] = bm::Counter{2, bm::Counter::kAvgIterations}; -} -BENCHMARK(BM_Counters_AvgIterations); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_AvgIterations %console_report " - "bar=%hrfloat foo=%hrfloat$"}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_AvgIterations\",$"}, - {"\"run_name\": \"BM_Counters_AvgIterations\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, - {{"^\"BM_Counters_AvgIterations\",%csv_report,%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckAvgIterations(Results const& e) { - double its = e.NumIterations(); - // check that the values are within 0.1% of the expected value - CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, 1. / its, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 2. / its, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_AvgIterations", &CheckAvgIterations); - -// ========================================================================= // -// ----------------- AvgIterationsRate Counters Output ---------------- // -// ========================================================================= // - -void BM_Counters_kAvgIterationsRate(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters["foo"] = bm::Counter{1, bm::Counter::kAvgIterationsRate}; - state.counters["bar"] = - bm::Counter{2, bm::Counter::kIsRate | bm::Counter::kAvgIterations}; -} -BENCHMARK(BM_Counters_kAvgIterationsRate); -ADD_CASES(TC_ConsoleOut, {{"^BM_Counters_kAvgIterationsRate " - "%console_report bar=%hrfloat/s foo=%hrfloat/s$"}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_kAvgIterationsRate\",$"}, - {"\"run_name\": \"BM_Counters_kAvgIterationsRate\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 0,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"bar\": %float,$", MR_Next}, - {"\"foo\": %float$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_CSVOut, {{"^\"BM_Counters_kAvgIterationsRate\",%csv_report," - "%float,%float$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckAvgIterationsRate(Results const& e) { - double its = e.NumIterations(); - double t = e.DurationCPUTime(); // this (and not real time) is the time used - // check that the values are within 0.1% of the expected values - CHECK_FLOAT_COUNTER_VALUE(e, "foo", EQ, 1. / its / t, 0.001); - CHECK_FLOAT_COUNTER_VALUE(e, "bar", EQ, 2. / its / t, 0.001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_kAvgIterationsRate", - &CheckAvgIterationsRate); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/user_counters_thousands_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/user_counters_thousands_test.cc deleted file mode 100644 index 21d8285dedc..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/test/user_counters_thousands_test.cc +++ /dev/null @@ -1,173 +0,0 @@ - -#undef NDEBUG - -#include "benchmark/benchmark.h" -#include "output_test.h" - -// ========================================================================= // -// ------------------------ Thousands Customisation ------------------------ // -// ========================================================================= // - -void BM_Counters_Thousands(benchmark::State& state) { - for (auto _ : state) { - } - namespace bm = benchmark; - state.counters.insert({ - {"t0_1000000DefaultBase", - bm::Counter(1000 * 1000, bm::Counter::kDefaults)}, - {"t1_1000000Base1000", bm::Counter(1000 * 1000, bm::Counter::kDefaults, - benchmark::Counter::OneK::kIs1000)}, - {"t2_1000000Base1024", bm::Counter(1000 * 1000, bm::Counter::kDefaults, - benchmark::Counter::OneK::kIs1024)}, - {"t3_1048576Base1000", bm::Counter(1024 * 1024, bm::Counter::kDefaults, - benchmark::Counter::OneK::kIs1000)}, - {"t4_1048576Base1024", bm::Counter(1024 * 1024, bm::Counter::kDefaults, - benchmark::Counter::OneK::kIs1024)}, - }); -} -BENCHMARK(BM_Counters_Thousands)->Repetitions(2); -ADD_CASES( - TC_ConsoleOut, - { - {"^BM_Counters_Thousands/repeats:2 %console_report " - "t0_1000000DefaultBase=1000k " - "t1_1000000Base1000=1000k t2_1000000Base1024=976.56[23]k " - "t3_1048576Base1000=1048.58k t4_1048576Base1024=1024k$"}, - {"^BM_Counters_Thousands/repeats:2 %console_report " - "t0_1000000DefaultBase=1000k " - "t1_1000000Base1000=1000k t2_1000000Base1024=976.56[23]k " - "t3_1048576Base1000=1048.58k t4_1048576Base1024=1024k$"}, - {"^BM_Counters_Thousands/repeats:2_mean %console_report " - "t0_1000000DefaultBase=1000k t1_1000000Base1000=1000k " - "t2_1000000Base1024=976.56[23]k t3_1048576Base1000=1048.58k " - "t4_1048576Base1024=1024k$"}, - {"^BM_Counters_Thousands/repeats:2_median %console_report " - "t0_1000000DefaultBase=1000k t1_1000000Base1000=1000k " - "t2_1000000Base1024=976.56[23]k t3_1048576Base1000=1048.58k " - "t4_1048576Base1024=1024k$"}, - {"^BM_Counters_Thousands/repeats:2_stddev %console_time_only_report [ " - "]*2 t0_1000000DefaultBase=0 t1_1000000Base1000=0 " - "t2_1000000Base1024=0 t3_1048576Base1000=0 t4_1048576Base1024=0$"}, - }); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_Thousands/repeats:2\",$"}, - {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"repetition_index\": 0,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"t0_1000000DefaultBase\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t1_1000000Base1000\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t2_1000000Base1024\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t3_1048576Base1000\": 1\\.048576(0)*e\\+(0)*6,$", MR_Next}, - {"\"t4_1048576Base1024\": 1\\.048576(0)*e\\+(0)*6$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_Thousands/repeats:2\",$"}, - {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, - {"\"run_type\": \"iteration\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"repetition_index\": 1,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"iterations\": %int,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"t0_1000000DefaultBase\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t1_1000000Base1000\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t2_1000000Base1024\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t3_1048576Base1000\": 1\\.048576(0)*e\\+(0)*6,$", MR_Next}, - {"\"t4_1048576Base1024\": 1\\.048576(0)*e\\+(0)*6$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_Thousands/repeats:2_mean\",$"}, - {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"mean\",$", MR_Next}, - {"\"iterations\": 2,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"t0_1000000DefaultBase\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t1_1000000Base1000\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t2_1000000Base1024\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t3_1048576Base1000\": 1\\.048576(0)*e\\+(0)*6,$", MR_Next}, - {"\"t4_1048576Base1024\": 1\\.048576(0)*e\\+(0)*6$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_Thousands/repeats:2_median\",$"}, - {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"median\",$", MR_Next}, - {"\"iterations\": 2,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"t0_1000000DefaultBase\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t1_1000000Base1000\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t2_1000000Base1024\": 1\\.(0)*e\\+(0)*6,$", MR_Next}, - {"\"t3_1048576Base1000\": 1\\.048576(0)*e\\+(0)*6,$", MR_Next}, - {"\"t4_1048576Base1024\": 1\\.048576(0)*e\\+(0)*6$", MR_Next}, - {"}", MR_Next}}); -ADD_CASES(TC_JSONOut, - {{"\"name\": \"BM_Counters_Thousands/repeats:2_stddev\",$"}, - {"\"run_name\": \"BM_Counters_Thousands/repeats:2\",$", MR_Next}, - {"\"run_type\": \"aggregate\",$", MR_Next}, - {"\"repetitions\": 2,$", MR_Next}, - {"\"threads\": 1,$", MR_Next}, - {"\"aggregate_name\": \"stddev\",$", MR_Next}, - {"\"iterations\": 2,$", MR_Next}, - {"\"real_time\": %float,$", MR_Next}, - {"\"cpu_time\": %float,$", MR_Next}, - {"\"time_unit\": \"ns\",$", MR_Next}, - {"\"t0_1000000DefaultBase\": 0\\.(0)*e\\+(0)*,$", MR_Next}, - {"\"t1_1000000Base1000\": 0\\.(0)*e\\+(0)*,$", MR_Next}, - {"\"t2_1000000Base1024\": 0\\.(0)*e\\+(0)*,$", MR_Next}, - {"\"t3_1048576Base1000\": 0\\.(0)*e\\+(0)*,$", MR_Next}, - {"\"t4_1048576Base1024\": 0\\.(0)*e\\+(0)*$", MR_Next}, - {"}", MR_Next}}); - -ADD_CASES( - TC_CSVOut, - {{"^\"BM_Counters_Thousands/" - "repeats:2\",%csv_report,1e\\+(0)*6,1e\\+(0)*6,1e\\+(0)*6,1\\.04858e\\+(" - "0)*6,1\\.04858e\\+(0)*6$"}, - {"^\"BM_Counters_Thousands/" - "repeats:2\",%csv_report,1e\\+(0)*6,1e\\+(0)*6,1e\\+(0)*6,1\\.04858e\\+(" - "0)*6,1\\.04858e\\+(0)*6$"}, - {"^\"BM_Counters_Thousands/" - "repeats:2_mean\",%csv_report,1e\\+(0)*6,1e\\+(0)*6,1e\\+(0)*6,1\\." - "04858e\\+(0)*6,1\\.04858e\\+(0)*6$"}, - {"^\"BM_Counters_Thousands/" - "repeats:2_median\",%csv_report,1e\\+(0)*6,1e\\+(0)*6,1e\\+(0)*6,1\\." - "04858e\\+(0)*6,1\\.04858e\\+(0)*6$"}, - {"^\"BM_Counters_Thousands/repeats:2_stddev\",%csv_report,0,0,0,0,0$"}}); -// VS2013 does not allow this function to be passed as a lambda argument -// to CHECK_BENCHMARK_RESULTS() -void CheckThousands(Results const& e) { - if (e.name != "BM_Counters_Thousands/repeats:2") - return; // Do not check the aggregates! - - // check that the values are within 0.01% of the expected values - CHECK_FLOAT_COUNTER_VALUE(e, "t0_1000000DefaultBase", EQ, 1000 * 1000, - 0.0001); - CHECK_FLOAT_COUNTER_VALUE(e, "t1_1000000Base1000", EQ, 1000 * 1000, 0.0001); - CHECK_FLOAT_COUNTER_VALUE(e, "t2_1000000Base1024", EQ, 1000 * 1000, 0.0001); - CHECK_FLOAT_COUNTER_VALUE(e, "t3_1048576Base1000", EQ, 1024 * 1024, 0.0001); - CHECK_FLOAT_COUNTER_VALUE(e, "t4_1048576Base1024", EQ, 1024 * 1024, 0.0001); -} -CHECK_BENCHMARK_RESULTS("BM_Counters_Thousands", &CheckThousands); - -// ========================================================================= // -// --------------------------- TEST CASES END ------------------------------ // -// ========================================================================= // - -int main(int argc, char* argv[]) { RunOutputTests(argc, argv); } diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/compare.py b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/compare.py deleted file mode 100755 index 539ace6fb16..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/compare.py +++ /dev/null @@ -1,408 +0,0 @@ -#!/usr/bin/env python - -import unittest -""" -compare.py - versatile benchmark output compare tool -""" - -import argparse -from argparse import ArgumentParser -import sys -import gbench -from gbench import util, report -from gbench.util import * - - -def check_inputs(in1, in2, flags): - """ - Perform checking on the user provided inputs and diagnose any abnormalities - """ - in1_kind, in1_err = classify_input_file(in1) - in2_kind, in2_err = classify_input_file(in2) - output_file = find_benchmark_flag('--benchmark_out=', flags) - output_type = find_benchmark_flag('--benchmark_out_format=', flags) - if in1_kind == IT_Executable and in2_kind == IT_Executable and output_file: - print(("WARNING: '--benchmark_out=%s' will be passed to both " - "benchmarks causing it to be overwritten") % output_file) - if in1_kind == IT_JSON and in2_kind == IT_JSON and len(flags) > 0: - print("WARNING: passing optional flags has no effect since both " - "inputs are JSON") - if output_type is not None and output_type != 'json': - print(("ERROR: passing '--benchmark_out_format=%s' to 'compare.py`" - " is not supported.") % output_type) - sys.exit(1) - - -def create_parser(): - parser = ArgumentParser( - description='versatile benchmark output compare tool') - - parser.add_argument( - '-a', - '--display_aggregates_only', - dest='display_aggregates_only', - action="store_true", - help="If there are repetitions, by default, we display everything - the" - " actual runs, and the aggregates computed. Sometimes, it is " - "desirable to only view the aggregates. E.g. when there are a lot " - "of repetitions. Do note that only the display is affected. " - "Internally, all the actual runs are still used, e.g. for U test.") - - utest = parser.add_argument_group() - utest.add_argument( - '--no-utest', - dest='utest', - default=True, - action="store_false", - help="The tool can do a two-tailed Mann-Whitney U test with the null hypothesis that it is equally likely that a randomly selected value from one sample will be less than or greater than a randomly selected value from a second sample.\nWARNING: requires **LARGE** (no less than {}) number of repetitions to be meaningful!\nThe test is being done by default, if at least {} repetitions were done.\nThis option can disable the U Test.".format(report.UTEST_OPTIMAL_REPETITIONS, report.UTEST_MIN_REPETITIONS)) - alpha_default = 0.05 - utest.add_argument( - "--alpha", - dest='utest_alpha', - default=alpha_default, - type=float, - help=("significance level alpha. if the calculated p-value is below this value, then the result is said to be statistically significant and the null hypothesis is rejected.\n(default: %0.4f)") % - alpha_default) - - subparsers = parser.add_subparsers( - help='This tool has multiple modes of operation:', - dest='mode') - - parser_a = subparsers.add_parser( - 'benchmarks', - help='The most simple use-case, compare all the output of these two benchmarks') - baseline = parser_a.add_argument_group( - 'baseline', 'The benchmark baseline') - baseline.add_argument( - 'test_baseline', - metavar='test_baseline', - type=argparse.FileType('r'), - nargs=1, - help='A benchmark executable or JSON output file') - contender = parser_a.add_argument_group( - 'contender', 'The benchmark that will be compared against the baseline') - contender.add_argument( - 'test_contender', - metavar='test_contender', - type=argparse.FileType('r'), - nargs=1, - help='A benchmark executable or JSON output file') - parser_a.add_argument( - 'benchmark_options', - metavar='benchmark_options', - nargs=argparse.REMAINDER, - help='Arguments to pass when running benchmark executables') - - parser_b = subparsers.add_parser( - 'filters', help='Compare filter one with the filter two of benchmark') - baseline = parser_b.add_argument_group( - 'baseline', 'The benchmark baseline') - baseline.add_argument( - 'test', - metavar='test', - type=argparse.FileType('r'), - nargs=1, - help='A benchmark executable or JSON output file') - baseline.add_argument( - 'filter_baseline', - metavar='filter_baseline', - type=str, - nargs=1, - help='The first filter, that will be used as baseline') - contender = parser_b.add_argument_group( - 'contender', 'The benchmark that will be compared against the baseline') - contender.add_argument( - 'filter_contender', - metavar='filter_contender', - type=str, - nargs=1, - help='The second filter, that will be compared against the baseline') - parser_b.add_argument( - 'benchmark_options', - metavar='benchmark_options', - nargs=argparse.REMAINDER, - help='Arguments to pass when running benchmark executables') - - parser_c = subparsers.add_parser( - 'benchmarksfiltered', - help='Compare filter one of first benchmark with filter two of the second benchmark') - baseline = parser_c.add_argument_group( - 'baseline', 'The benchmark baseline') - baseline.add_argument( - 'test_baseline', - metavar='test_baseline', - type=argparse.FileType('r'), - nargs=1, - help='A benchmark executable or JSON output file') - baseline.add_argument( - 'filter_baseline', - metavar='filter_baseline', - type=str, - nargs=1, - help='The first filter, that will be used as baseline') - contender = parser_c.add_argument_group( - 'contender', 'The benchmark that will be compared against the baseline') - contender.add_argument( - 'test_contender', - metavar='test_contender', - type=argparse.FileType('r'), - nargs=1, - help='The second benchmark executable or JSON output file, that will be compared against the baseline') - contender.add_argument( - 'filter_contender', - metavar='filter_contender', - type=str, - nargs=1, - help='The second filter, that will be compared against the baseline') - parser_c.add_argument( - 'benchmark_options', - metavar='benchmark_options', - nargs=argparse.REMAINDER, - help='Arguments to pass when running benchmark executables') - - return parser - - -def main(): - # Parse the command line flags - parser = create_parser() - args, unknown_args = parser.parse_known_args() - if args.mode is None: - parser.print_help() - exit(1) - assert not unknown_args - benchmark_options = args.benchmark_options - - if args.mode == 'benchmarks': - test_baseline = args.test_baseline[0].name - test_contender = args.test_contender[0].name - filter_baseline = '' - filter_contender = '' - - # NOTE: if test_baseline == test_contender, you are analyzing the stdev - - description = 'Comparing %s to %s' % (test_baseline, test_contender) - elif args.mode == 'filters': - test_baseline = args.test[0].name - test_contender = args.test[0].name - filter_baseline = args.filter_baseline[0] - filter_contender = args.filter_contender[0] - - # NOTE: if filter_baseline == filter_contender, you are analyzing the - # stdev - - description = 'Comparing %s to %s (from %s)' % ( - filter_baseline, filter_contender, args.test[0].name) - elif args.mode == 'benchmarksfiltered': - test_baseline = args.test_baseline[0].name - test_contender = args.test_contender[0].name - filter_baseline = args.filter_baseline[0] - filter_contender = args.filter_contender[0] - - # NOTE: if test_baseline == test_contender and - # filter_baseline == filter_contender, you are analyzing the stdev - - description = 'Comparing %s (from %s) to %s (from %s)' % ( - filter_baseline, test_baseline, filter_contender, test_contender) - else: - # should never happen - print("Unrecognized mode of operation: '%s'" % args.mode) - parser.print_help() - exit(1) - - check_inputs(test_baseline, test_contender, benchmark_options) - - if args.display_aggregates_only: - benchmark_options += ['--benchmark_display_aggregates_only=true'] - - options_baseline = [] - options_contender = [] - - if filter_baseline and filter_contender: - options_baseline = ['--benchmark_filter=%s' % filter_baseline] - options_contender = ['--benchmark_filter=%s' % filter_contender] - - # Run the benchmarks and report the results - json1 = json1_orig = gbench.util.run_or_load_benchmark( - test_baseline, benchmark_options + options_baseline) - json2 = json2_orig = gbench.util.run_or_load_benchmark( - test_contender, benchmark_options + options_contender) - - # Now, filter the benchmarks so that the difference report can work - if filter_baseline and filter_contender: - replacement = '[%s vs. %s]' % (filter_baseline, filter_contender) - json1 = gbench.report.filter_benchmark( - json1_orig, filter_baseline, replacement) - json2 = gbench.report.filter_benchmark( - json2_orig, filter_contender, replacement) - - # Diff and output - output_lines = gbench.report.generate_difference_report( - json1, json2, args.display_aggregates_only, - args.utest, args.utest_alpha) - print(description) - for ln in output_lines: - print(ln) - - -class TestParser(unittest.TestCase): - def setUp(self): - self.parser = create_parser() - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'gbench', - 'Inputs') - self.testInput0 = os.path.join(testInputs, 'test1_run1.json') - self.testInput1 = os.path.join(testInputs, 'test1_run2.json') - - def test_benchmarks_basic(self): - parsed = self.parser.parse_args( - ['benchmarks', self.testInput0, self.testInput1]) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertFalse(parsed.benchmark_options) - - def test_benchmarks_basic_without_utest(self): - parsed = self.parser.parse_args( - ['--no-utest', 'benchmarks', self.testInput0, self.testInput1]) - self.assertFalse(parsed.display_aggregates_only) - self.assertFalse(parsed.utest) - self.assertEqual(parsed.utest_alpha, 0.05) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertFalse(parsed.benchmark_options) - - def test_benchmarks_basic_display_aggregates_only(self): - parsed = self.parser.parse_args( - ['-a', 'benchmarks', self.testInput0, self.testInput1]) - self.assertTrue(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertFalse(parsed.benchmark_options) - - def test_benchmarks_basic_with_utest_alpha(self): - parsed = self.parser.parse_args( - ['--alpha=0.314', 'benchmarks', self.testInput0, self.testInput1]) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.utest_alpha, 0.314) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertFalse(parsed.benchmark_options) - - def test_benchmarks_basic_without_utest_with_utest_alpha(self): - parsed = self.parser.parse_args( - ['--no-utest', '--alpha=0.314', 'benchmarks', self.testInput0, self.testInput1]) - self.assertFalse(parsed.display_aggregates_only) - self.assertFalse(parsed.utest) - self.assertEqual(parsed.utest_alpha, 0.314) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertFalse(parsed.benchmark_options) - - def test_benchmarks_with_remainder(self): - parsed = self.parser.parse_args( - ['benchmarks', self.testInput0, self.testInput1, 'd']) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.benchmark_options, ['d']) - - def test_benchmarks_with_remainder_after_doubleminus(self): - parsed = self.parser.parse_args( - ['benchmarks', self.testInput0, self.testInput1, '--', 'e']) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'benchmarks') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.benchmark_options, ['e']) - - def test_filters_basic(self): - parsed = self.parser.parse_args( - ['filters', self.testInput0, 'c', 'd']) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'filters') - self.assertEqual(parsed.test[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.filter_contender[0], 'd') - self.assertFalse(parsed.benchmark_options) - - def test_filters_with_remainder(self): - parsed = self.parser.parse_args( - ['filters', self.testInput0, 'c', 'd', 'e']) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'filters') - self.assertEqual(parsed.test[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.filter_contender[0], 'd') - self.assertEqual(parsed.benchmark_options, ['e']) - - def test_filters_with_remainder_after_doubleminus(self): - parsed = self.parser.parse_args( - ['filters', self.testInput0, 'c', 'd', '--', 'f']) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'filters') - self.assertEqual(parsed.test[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.filter_contender[0], 'd') - self.assertEqual(parsed.benchmark_options, ['f']) - - def test_benchmarksfiltered_basic(self): - parsed = self.parser.parse_args( - ['benchmarksfiltered', self.testInput0, 'c', self.testInput1, 'e']) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'benchmarksfiltered') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.filter_contender[0], 'e') - self.assertFalse(parsed.benchmark_options) - - def test_benchmarksfiltered_with_remainder(self): - parsed = self.parser.parse_args( - ['benchmarksfiltered', self.testInput0, 'c', self.testInput1, 'e', 'f']) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'benchmarksfiltered') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.filter_contender[0], 'e') - self.assertEqual(parsed.benchmark_options[0], 'f') - - def test_benchmarksfiltered_with_remainder_after_doubleminus(self): - parsed = self.parser.parse_args( - ['benchmarksfiltered', self.testInput0, 'c', self.testInput1, 'e', '--', 'g']) - self.assertFalse(parsed.display_aggregates_only) - self.assertTrue(parsed.utest) - self.assertEqual(parsed.mode, 'benchmarksfiltered') - self.assertEqual(parsed.test_baseline[0].name, self.testInput0) - self.assertEqual(parsed.filter_baseline[0], 'c') - self.assertEqual(parsed.test_contender[0].name, self.testInput1) - self.assertEqual(parsed.filter_contender[0], 'e') - self.assertEqual(parsed.benchmark_options[0], 'g') - - -if __name__ == '__main__': - # unittest.main() - main() - -# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 -# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; -# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test1_run1.json b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test1_run1.json deleted file mode 100644 index 601e327aefb..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test1_run1.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "context": { - "date": "2016-08-02 17:44:46", - "num_cpus": 4, - "mhz_per_cpu": 4228, - "cpu_scaling_enabled": false, - "library_build_type": "release" - }, - "benchmarks": [ - { - "name": "BM_SameTimes", - "iterations": 1000, - "real_time": 10, - "cpu_time": 10, - "time_unit": "ns" - }, - { - "name": "BM_2xFaster", - "iterations": 1000, - "real_time": 50, - "cpu_time": 50, - "time_unit": "ns" - }, - { - "name": "BM_2xSlower", - "iterations": 1000, - "real_time": 50, - "cpu_time": 50, - "time_unit": "ns" - }, - { - "name": "BM_1PercentFaster", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_1PercentSlower", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_10PercentFaster", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_10PercentSlower", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_100xSlower", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_100xFaster", - "iterations": 1000, - "real_time": 10000, - "cpu_time": 10000, - "time_unit": "ns" - }, - { - "name": "BM_10PercentCPUToTime", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_ThirdFaster", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "MyComplexityTest_BigO", - "run_name": "MyComplexityTest", - "run_type": "aggregate", - "aggregate_name": "BigO", - "cpu_coefficient": 4.2749856294592886e+00, - "real_coefficient": 6.4789275289789780e+00, - "big_o": "N", - "time_unit": "ns" - }, - { - "name": "MyComplexityTest_RMS", - "run_name": "MyComplexityTest", - "run_type": "aggregate", - "aggregate_name": "RMS", - "rms": 4.5097802512472874e-03 - }, - { - "name": "BM_NotBadTimeUnit", - "iterations": 1000, - "real_time": 0.4, - "cpu_time": 0.5, - "time_unit": "s" - }, - { - "name": "BM_DifferentTimeUnit", - "iterations": 1, - "real_time": 1, - "cpu_time": 1, - "time_unit": "s" - } - ] -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test1_run2.json b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test1_run2.json deleted file mode 100644 index 3cbcf39b0c9..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test1_run2.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - "context": { - "date": "2016-08-02 17:44:46", - "num_cpus": 4, - "mhz_per_cpu": 4228, - "cpu_scaling_enabled": false, - "library_build_type": "release" - }, - "benchmarks": [ - { - "name": "BM_SameTimes", - "iterations": 1000, - "real_time": 10, - "cpu_time": 10, - "time_unit": "ns" - }, - { - "name": "BM_2xFaster", - "iterations": 1000, - "real_time": 25, - "cpu_time": 25, - "time_unit": "ns" - }, - { - "name": "BM_2xSlower", - "iterations": 20833333, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_1PercentFaster", - "iterations": 1000, - "real_time": 98.9999999, - "cpu_time": 98.9999999, - "time_unit": "ns" - }, - { - "name": "BM_1PercentSlower", - "iterations": 1000, - "real_time": 100.9999999, - "cpu_time": 100.9999999, - "time_unit": "ns" - }, - { - "name": "BM_10PercentFaster", - "iterations": 1000, - "real_time": 90, - "cpu_time": 90, - "time_unit": "ns" - }, - { - "name": "BM_10PercentSlower", - "iterations": 1000, - "real_time": 110, - "cpu_time": 110, - "time_unit": "ns" - }, - { - "name": "BM_100xSlower", - "iterations": 1000, - "real_time": 1.0000e+04, - "cpu_time": 1.0000e+04, - "time_unit": "ns" - }, - { - "name": "BM_100xFaster", - "iterations": 1000, - "real_time": 100, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_10PercentCPUToTime", - "iterations": 1000, - "real_time": 110, - "cpu_time": 90, - "time_unit": "ns" - }, - { - "name": "BM_ThirdFaster", - "iterations": 1000, - "real_time": 66.665, - "cpu_time": 66.664, - "time_unit": "ns" - }, - { - "name": "MyComplexityTest_BigO", - "run_name": "MyComplexityTest", - "run_type": "aggregate", - "aggregate_name": "BigO", - "cpu_coefficient": 5.6215779594361486e+00, - "real_coefficient": 5.6288314793554610e+00, - "big_o": "N", - "time_unit": "ns" - }, - { - "name": "MyComplexityTest_RMS", - "run_name": "MyComplexityTest", - "run_type": "aggregate", - "aggregate_name": "RMS", - "rms": 3.3128901852342174e-03 - }, - { - "name": "BM_NotBadTimeUnit", - "iterations": 1000, - "real_time": 0.04, - "cpu_time": 0.6, - "time_unit": "s" - }, - { - "name": "BM_DifferentTimeUnit", - "iterations": 1, - "real_time": 1, - "cpu_time": 1, - "time_unit": "ns" - } - ] -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test2_run.json b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test2_run.json deleted file mode 100644 index 15bc6980304..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test2_run.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "context": { - "date": "2016-08-02 17:44:46", - "num_cpus": 4, - "mhz_per_cpu": 4228, - "cpu_scaling_enabled": false, - "library_build_type": "release" - }, - "benchmarks": [ - { - "name": "BM_Hi", - "iterations": 1234, - "real_time": 42, - "cpu_time": 24, - "time_unit": "ms" - }, - { - "name": "BM_Zero", - "iterations": 1000, - "real_time": 10, - "cpu_time": 10, - "time_unit": "ns" - }, - { - "name": "BM_Zero/4", - "iterations": 4000, - "real_time": 40, - "cpu_time": 40, - "time_unit": "ns" - }, - { - "name": "Prefix/BM_Zero", - "iterations": 2000, - "real_time": 20, - "cpu_time": 20, - "time_unit": "ns" - }, - { - "name": "Prefix/BM_Zero/3", - "iterations": 3000, - "real_time": 30, - "cpu_time": 30, - "time_unit": "ns" - }, - { - "name": "BM_One", - "iterations": 5000, - "real_time": 5, - "cpu_time": 5, - "time_unit": "ns" - }, - { - "name": "BM_One/4", - "iterations": 2000, - "real_time": 20, - "cpu_time": 20, - "time_unit": "ns" - }, - { - "name": "Prefix/BM_One", - "iterations": 1000, - "real_time": 10, - "cpu_time": 10, - "time_unit": "ns" - }, - { - "name": "Prefix/BM_One/3", - "iterations": 1500, - "real_time": 15, - "cpu_time": 15, - "time_unit": "ns" - }, - { - "name": "BM_Bye", - "iterations": 5321, - "real_time": 11, - "cpu_time": 63, - "time_unit": "ns" - } - ] -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test3_run0.json b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test3_run0.json deleted file mode 100644 index 49f8b061437..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test3_run0.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "context": { - "date": "2016-08-02 17:44:46", - "num_cpus": 4, - "mhz_per_cpu": 4228, - "cpu_scaling_enabled": false, - "library_build_type": "release" - }, - "benchmarks": [ - { - "name": "BM_One", - "run_type": "aggregate", - "iterations": 1000, - "real_time": 10, - "cpu_time": 100, - "time_unit": "ns" - }, - { - "name": "BM_Two", - "iterations": 1000, - "real_time": 9, - "cpu_time": 90, - "time_unit": "ns" - }, - { - "name": "BM_Two", - "iterations": 1000, - "real_time": 8, - "cpu_time": 86, - "time_unit": "ns" - }, - { - "name": "short", - "run_type": "aggregate", - "iterations": 1000, - "real_time": 8, - "cpu_time": 80, - "time_unit": "ns" - }, - { - "name": "short", - "run_type": "aggregate", - "iterations": 1000, - "real_time": 8, - "cpu_time": 77, - "time_unit": "ns" - }, - { - "name": "medium", - "run_type": "iteration", - "iterations": 1000, - "real_time": 8, - "cpu_time": 80, - "time_unit": "ns" - }, - { - "name": "medium", - "run_type": "iteration", - "iterations": 1000, - "real_time": 9, - "cpu_time": 82, - "time_unit": "ns" - } - ] -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test3_run1.json b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test3_run1.json deleted file mode 100644 index acc5ba17aed..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/Inputs/test3_run1.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "context": { - "date": "2016-08-02 17:44:46", - "num_cpus": 4, - "mhz_per_cpu": 4228, - "cpu_scaling_enabled": false, - "library_build_type": "release" - }, - "benchmarks": [ - { - "name": "BM_One", - "iterations": 1000, - "real_time": 9, - "cpu_time": 110, - "time_unit": "ns" - }, - { - "name": "BM_Two", - "run_type": "aggregate", - "iterations": 1000, - "real_time": 10, - "cpu_time": 89, - "time_unit": "ns" - }, - { - "name": "BM_Two", - "iterations": 1000, - "real_time": 7, - "cpu_time": 72, - "time_unit": "ns" - }, - { - "name": "short", - "run_type": "aggregate", - "iterations": 1000, - "real_time": 7, - "cpu_time": 75, - "time_unit": "ns" - }, - { - "name": "short", - "run_type": "aggregate", - "iterations": 762, - "real_time": 4.54, - "cpu_time": 66.6, - "time_unit": "ns" - }, - { - "name": "short", - "run_type": "iteration", - "iterations": 1000, - "real_time": 800, - "cpu_time": 1, - "time_unit": "ns" - }, - { - "name": "medium", - "run_type": "iteration", - "iterations": 1200, - "real_time": 5, - "cpu_time": 53, - "time_unit": "ns" - } - ] -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/__init__.py b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/__init__.py deleted file mode 100644 index fce1a1acfbb..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Google Benchmark tooling""" - -__author__ = 'Eric Fiselier' -__email__ = 'eric@efcs.ca' -__versioninfo__ = (0, 5, 0) -__version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev' - -__all__ = [] diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/report.py b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/report.py deleted file mode 100644 index 5bd3a8d85d6..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/report.py +++ /dev/null @@ -1,541 +0,0 @@ -import unittest -"""report.py - Utilities for reporting statistics about benchmark results -""" -import os -import re -import copy - -from scipy.stats import mannwhitneyu - - -class BenchmarkColor(object): - def __init__(self, name, code): - self.name = name - self.code = code - - def __repr__(self): - return '%s%r' % (self.__class__.__name__, - (self.name, self.code)) - - def __format__(self, format): - return self.code - - -# Benchmark Colors Enumeration -BC_NONE = BenchmarkColor('NONE', '') -BC_MAGENTA = BenchmarkColor('MAGENTA', '\033[95m') -BC_CYAN = BenchmarkColor('CYAN', '\033[96m') -BC_OKBLUE = BenchmarkColor('OKBLUE', '\033[94m') -BC_OKGREEN = BenchmarkColor('OKGREEN', '\033[32m') -BC_HEADER = BenchmarkColor('HEADER', '\033[92m') -BC_WARNING = BenchmarkColor('WARNING', '\033[93m') -BC_WHITE = BenchmarkColor('WHITE', '\033[97m') -BC_FAIL = BenchmarkColor('FAIL', '\033[91m') -BC_ENDC = BenchmarkColor('ENDC', '\033[0m') -BC_BOLD = BenchmarkColor('BOLD', '\033[1m') -BC_UNDERLINE = BenchmarkColor('UNDERLINE', '\033[4m') - -UTEST_MIN_REPETITIONS = 2 -UTEST_OPTIMAL_REPETITIONS = 9 # Lowest reasonable number, More is better. -UTEST_COL_NAME = "_pvalue" - - -def color_format(use_color, fmt_str, *args, **kwargs): - """ - Return the result of 'fmt_str.format(*args, **kwargs)' after transforming - 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' - is False then all color codes in 'args' and 'kwargs' are replaced with - the empty string. - """ - assert use_color is True or use_color is False - if not use_color: - args = [arg if not isinstance(arg, BenchmarkColor) else BC_NONE - for arg in args] - kwargs = {key: arg if not isinstance(arg, BenchmarkColor) else BC_NONE - for key, arg in kwargs.items()} - return fmt_str.format(*args, **kwargs) - - -def find_longest_name(benchmark_list): - """ - Return the length of the longest benchmark name in a given list of - benchmark JSON objects - """ - longest_name = 1 - for bc in benchmark_list: - if len(bc['name']) > longest_name: - longest_name = len(bc['name']) - return longest_name - - -def calculate_change(old_val, new_val): - """ - Return a float representing the decimal change between old_val and new_val. - """ - if old_val == 0 and new_val == 0: - return 0.0 - if old_val == 0: - return float(new_val - old_val) / (float(old_val + new_val) / 2) - return float(new_val - old_val) / abs(old_val) - - -def filter_benchmark(json_orig, family, replacement=""): - """ - Apply a filter to the json, and only leave the 'family' of benchmarks. - """ - regex = re.compile(family) - filtered = {} - filtered['benchmarks'] = [] - for be in json_orig['benchmarks']: - if not regex.search(be['name']): - continue - filteredbench = copy.deepcopy(be) # Do NOT modify the old name! - filteredbench['name'] = regex.sub(replacement, filteredbench['name']) - filtered['benchmarks'].append(filteredbench) - return filtered - - -def get_unique_benchmark_names(json): - """ - While *keeping* the order, give all the unique 'names' used for benchmarks. - """ - seen = set() - uniqued = [x['name'] for x in json['benchmarks'] - if x['name'] not in seen and - (seen.add(x['name']) or True)] - return uniqued - - -def intersect(list1, list2): - """ - Given two lists, get a new list consisting of the elements only contained - in *both of the input lists*, while preserving the ordering. - """ - return [x for x in list1 if x in list2] - - -def is_potentially_comparable_benchmark(x): - return ('time_unit' in x and 'real_time' in x and 'cpu_time' in x) - - -def partition_benchmarks(json1, json2): - """ - While preserving the ordering, find benchmarks with the same names in - both of the inputs, and group them. - (i.e. partition/filter into groups with common name) - """ - json1_unique_names = get_unique_benchmark_names(json1) - json2_unique_names = get_unique_benchmark_names(json2) - names = intersect(json1_unique_names, json2_unique_names) - partitions = [] - for name in names: - time_unit = None - # Pick the time unit from the first entry of the lhs benchmark. - # We should be careful not to crash with unexpected input. - for x in json1['benchmarks']: - if (x['name'] == name and is_potentially_comparable_benchmark(x)): - time_unit = x['time_unit'] - break - if time_unit is None: - continue - # Filter by name and time unit. - # All the repetitions are assumed to be comparable. - lhs = [x for x in json1['benchmarks'] if x['name'] == name and - x['time_unit'] == time_unit] - rhs = [x for x in json2['benchmarks'] if x['name'] == name and - x['time_unit'] == time_unit] - partitions.append([lhs, rhs]) - return partitions - - -def extract_field(partition, field_name): - # The count of elements may be different. We want *all* of them. - lhs = [x[field_name] for x in partition[0]] - rhs = [x[field_name] for x in partition[1]] - return [lhs, rhs] - -def calc_utest(timings_cpu, timings_time): - min_rep_cnt = min(len(timings_time[0]), - len(timings_time[1]), - len(timings_cpu[0]), - len(timings_cpu[1])) - - # Does *everything* has at least UTEST_MIN_REPETITIONS repetitions? - if min_rep_cnt < UTEST_MIN_REPETITIONS: - return False, None, None - - time_pvalue = mannwhitneyu( - timings_time[0], timings_time[1], alternative='two-sided').pvalue - cpu_pvalue = mannwhitneyu( - timings_cpu[0], timings_cpu[1], alternative='two-sided').pvalue - - return (min_rep_cnt >= UTEST_OPTIMAL_REPETITIONS), cpu_pvalue, time_pvalue - -def print_utest(partition, utest_alpha, first_col_width, use_color=True): - def get_utest_color(pval): - return BC_FAIL if pval >= utest_alpha else BC_OKGREEN - - timings_time = extract_field(partition, 'real_time') - timings_cpu = extract_field(partition, 'cpu_time') - have_optimal_repetitions, cpu_pvalue, time_pvalue = calc_utest(timings_cpu, timings_time) - - # Check if we failed miserably with minimum required repetitions for utest - if not have_optimal_repetitions and cpu_pvalue is None and time_pvalue is None: - return [] - - dsc = "U Test, Repetitions: {} vs {}".format( - len(timings_cpu[0]), len(timings_cpu[1])) - dsc_color = BC_OKGREEN - - # We still got some results to show but issue a warning about it. - if not have_optimal_repetitions: - dsc_color = BC_WARNING - dsc += ". WARNING: Results unreliable! {}+ repetitions recommended.".format( - UTEST_OPTIMAL_REPETITIONS) - - special_str = "{}{:<{}s}{endc}{}{:16.4f}{endc}{}{:16.4f}{endc}{} {}" - - last_name = partition[0][0]['name'] - return [color_format(use_color, - special_str, - BC_HEADER, - "{}{}".format(last_name, UTEST_COL_NAME), - first_col_width, - get_utest_color(time_pvalue), time_pvalue, - get_utest_color(cpu_pvalue), cpu_pvalue, - dsc_color, dsc, - endc=BC_ENDC)] - - -def generate_difference_report( - json1, - json2, - display_aggregates_only=False, - utest=False, - utest_alpha=0.05, - use_color=True): - """ - Calculate and report the difference between each test of two benchmarks - runs specified as 'json1' and 'json2'. - """ - assert utest is True or utest is False - first_col_width = find_longest_name(json1['benchmarks']) - - def find_test(name): - for b in json2['benchmarks']: - if b['name'] == name: - return b - return None - - first_col_width = max( - first_col_width, - len('Benchmark')) - first_col_width += len(UTEST_COL_NAME) - first_line = "{:<{}s}Time CPU Time Old Time New CPU Old CPU New".format( - 'Benchmark', 12 + first_col_width) - output_strs = [first_line, '-' * len(first_line)] - - partitions = partition_benchmarks(json1, json2) - for partition in partitions: - # Careful, we may have different repetition count. - for i in range(min(len(partition[0]), len(partition[1]))): - bn = partition[0][i] - other_bench = partition[1][i] - - # *If* we were asked to only display aggregates, - # and if it is non-aggregate, then skip it. - if display_aggregates_only and 'run_type' in bn and 'run_type' in other_bench: - assert bn['run_type'] == other_bench['run_type'] - if bn['run_type'] != 'aggregate': - continue - - fmt_str = "{}{:<{}s}{endc}{}{:+16.4f}{endc}{}{:+16.4f}{endc}{:14.0f}{:14.0f}{endc}{:14.0f}{:14.0f}" - - def get_color(res): - if res > 0.05: - return BC_FAIL - elif res > -0.07: - return BC_WHITE - else: - return BC_CYAN - - tres = calculate_change(bn['real_time'], other_bench['real_time']) - cpures = calculate_change(bn['cpu_time'], other_bench['cpu_time']) - output_strs += [color_format(use_color, - fmt_str, - BC_HEADER, - bn['name'], - first_col_width, - get_color(tres), - tres, - get_color(cpures), - cpures, - bn['real_time'], - other_bench['real_time'], - bn['cpu_time'], - other_bench['cpu_time'], - endc=BC_ENDC)] - - # After processing the whole partition, if requested, do the U test. - if utest: - output_strs += print_utest(partition, - utest_alpha=utest_alpha, - first_col_width=first_col_width, - use_color=use_color) - - return output_strs - - -############################################################################### -# Unit tests - - -class TestGetUniqueBenchmarkNames(unittest.TestCase): - def load_results(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput = os.path.join(testInputs, 'test3_run0.json') - with open(testOutput, 'r') as f: - json = json.load(f) - return json - - def test_basic(self): - expect_lines = [ - 'BM_One', - 'BM_Two', - 'short', # These two are not sorted - 'medium', # These two are not sorted - ] - json = self.load_results() - output_lines = get_unique_benchmark_names(json) - print("\n") - print("\n".join(output_lines)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - self.assertEqual(expect_lines[i], output_lines[i]) - - -class TestReportDifference(unittest.TestCase): - def load_results(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput1 = os.path.join(testInputs, 'test1_run1.json') - testOutput2 = os.path.join(testInputs, 'test1_run2.json') - with open(testOutput1, 'r') as f: - json1 = json.load(f) - with open(testOutput2, 'r') as f: - json2 = json.load(f) - return json1, json2 - - def test_basic(self): - expect_lines = [ - ['BM_SameTimes', '+0.0000', '+0.0000', '10', '10', '10', '10'], - ['BM_2xFaster', '-0.5000', '-0.5000', '50', '25', '50', '25'], - ['BM_2xSlower', '+1.0000', '+1.0000', '50', '100', '50', '100'], - ['BM_1PercentFaster', '-0.0100', '-0.0100', '100', '99', '100', '99'], - ['BM_1PercentSlower', '+0.0100', '+0.0100', '100', '101', '100', '101'], - ['BM_10PercentFaster', '-0.1000', '-0.1000', '100', '90', '100', '90'], - ['BM_10PercentSlower', '+0.1000', '+0.1000', '100', '110', '100', '110'], - ['BM_100xSlower', '+99.0000', '+99.0000', - '100', '10000', '100', '10000'], - ['BM_100xFaster', '-0.9900', '-0.9900', - '10000', '100', '10000', '100'], - ['BM_10PercentCPUToTime', '+0.1000', - '-0.1000', '100', '110', '100', '90'], - ['BM_ThirdFaster', '-0.3333', '-0.3334', '100', '67', '100', '67'], - ['BM_NotBadTimeUnit', '-0.9000', '+0.2000', '0', '0', '0', '1'], - ] - json1, json2 = self.load_results() - output_lines_with_header = generate_difference_report( - json1, json2, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n") - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(len(parts), 7) - self.assertEqual(expect_lines[i], parts) - - -class TestReportDifferenceBetweenFamilies(unittest.TestCase): - def load_result(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput = os.path.join(testInputs, 'test2_run.json') - with open(testOutput, 'r') as f: - json = json.load(f) - return json - - def test_basic(self): - expect_lines = [ - ['.', '-0.5000', '-0.5000', '10', '5', '10', '5'], - ['./4', '-0.5000', '-0.5000', '40', '20', '40', '20'], - ['Prefix/.', '-0.5000', '-0.5000', '20', '10', '20', '10'], - ['Prefix/./3', '-0.5000', '-0.5000', '30', '15', '30', '15'], - ] - json = self.load_result() - json1 = filter_benchmark(json, "BM_Z.ro", ".") - json2 = filter_benchmark(json, "BM_O.e", ".") - output_lines_with_header = generate_difference_report( - json1, json2, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n") - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(len(parts), 7) - self.assertEqual(expect_lines[i], parts) - - -class TestReportDifferenceWithUTest(unittest.TestCase): - def load_results(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput1 = os.path.join(testInputs, 'test3_run0.json') - testOutput2 = os.path.join(testInputs, 'test3_run1.json') - with open(testOutput1, 'r') as f: - json1 = json.load(f) - with open(testOutput2, 'r') as f: - json2 = json.load(f) - return json1, json2 - - def test_utest(self): - expect_lines = [] - expect_lines = [ - ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'], - ['BM_Two', '+0.1111', '-0.0111', '9', '10', '90', '89'], - ['BM_Two', '-0.1250', '-0.1628', '8', '7', '86', '72'], - ['BM_Two_pvalue', - '0.6985', - '0.6985', - 'U', - 'Test,', - 'Repetitions:', - '2', - 'vs', - '2.', - 'WARNING:', - 'Results', - 'unreliable!', - '9+', - 'repetitions', - 'recommended.'], - ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'], - ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'], - ['short_pvalue', - '0.7671', - '0.1489', - 'U', - 'Test,', - 'Repetitions:', - '2', - 'vs', - '3.', - 'WARNING:', - 'Results', - 'unreliable!', - '9+', - 'repetitions', - 'recommended.'], - ['medium', '-0.3750', '-0.3375', '8', '5', '80', '53'], - ] - json1, json2 = self.load_results() - output_lines_with_header = generate_difference_report( - json1, json2, utest=True, utest_alpha=0.05, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n") - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(expect_lines[i], parts) - - -class TestReportDifferenceWithUTestWhileDisplayingAggregatesOnly( - unittest.TestCase): - def load_results(self): - import json - testInputs = os.path.join( - os.path.dirname( - os.path.realpath(__file__)), - 'Inputs') - testOutput1 = os.path.join(testInputs, 'test3_run0.json') - testOutput2 = os.path.join(testInputs, 'test3_run1.json') - with open(testOutput1, 'r') as f: - json1 = json.load(f) - with open(testOutput2, 'r') as f: - json2 = json.load(f) - return json1, json2 - - def test_utest(self): - expect_lines = [] - expect_lines = [ - ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'], - ['BM_Two', '+0.1111', '-0.0111', '9', '10', '90', '89'], - ['BM_Two', '-0.1250', '-0.1628', '8', '7', '86', '72'], - ['BM_Two_pvalue', - '0.6985', - '0.6985', - 'U', - 'Test,', - 'Repetitions:', - '2', - 'vs', - '2.', - 'WARNING:', - 'Results', - 'unreliable!', - '9+', - 'repetitions', - 'recommended.'], - ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'], - ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'], - ['short_pvalue', - '0.7671', - '0.1489', - 'U', - 'Test,', - 'Repetitions:', - '2', - 'vs', - '3.', - 'WARNING:', - 'Results', - 'unreliable!', - '9+', - 'repetitions', - 'recommended.'], - ] - json1, json2 = self.load_results() - output_lines_with_header = generate_difference_report( - json1, json2, display_aggregates_only=True, - utest=True, utest_alpha=0.05, use_color=False) - output_lines = output_lines_with_header[2:] - print("\n") - print("\n".join(output_lines_with_header)) - self.assertEqual(len(output_lines), len(expect_lines)) - for i in range(0, len(output_lines)): - parts = [x for x in output_lines[i].split(' ') if x] - self.assertEqual(expect_lines[i], parts) - - -if __name__ == '__main__': - unittest.main() - -# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 -# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; -# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/util.py b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/util.py deleted file mode 100644 index 1f8e8e2c479..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/gbench/util.py +++ /dev/null @@ -1,164 +0,0 @@ -"""util.py - General utilities for running, loading, and processing benchmarks -""" -import json -import os -import tempfile -import subprocess -import sys - -# Input file type enumeration -IT_Invalid = 0 -IT_JSON = 1 -IT_Executable = 2 - -_num_magic_bytes = 2 if sys.platform.startswith('win') else 4 - - -def is_executable_file(filename): - """ - Return 'True' if 'filename' names a valid file which is likely - an executable. A file is considered an executable if it starts with the - magic bytes for a EXE, Mach O, or ELF file. - """ - if not os.path.isfile(filename): - return False - with open(filename, mode='rb') as f: - magic_bytes = f.read(_num_magic_bytes) - if sys.platform == 'darwin': - return magic_bytes in [ - b'\xfe\xed\xfa\xce', # MH_MAGIC - b'\xce\xfa\xed\xfe', # MH_CIGAM - b'\xfe\xed\xfa\xcf', # MH_MAGIC_64 - b'\xcf\xfa\xed\xfe', # MH_CIGAM_64 - b'\xca\xfe\xba\xbe', # FAT_MAGIC - b'\xbe\xba\xfe\xca' # FAT_CIGAM - ] - elif sys.platform.startswith('win'): - return magic_bytes == b'MZ' - else: - return magic_bytes == b'\x7FELF' - - -def is_json_file(filename): - """ - Returns 'True' if 'filename' names a valid JSON output file. - 'False' otherwise. - """ - try: - with open(filename, 'r') as f: - json.load(f) - return True - except BaseException: - pass - return False - - -def classify_input_file(filename): - """ - Return a tuple (type, msg) where 'type' specifies the classified type - of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable - string represeting the error. - """ - ftype = IT_Invalid - err_msg = None - if not os.path.exists(filename): - err_msg = "'%s' does not exist" % filename - elif not os.path.isfile(filename): - err_msg = "'%s' does not name a file" % filename - elif is_executable_file(filename): - ftype = IT_Executable - elif is_json_file(filename): - ftype = IT_JSON - else: - err_msg = "'%s' does not name a valid benchmark executable or JSON file" % filename - return ftype, err_msg - - -def check_input_file(filename): - """ - Classify the file named by 'filename' and return the classification. - If the file is classified as 'IT_Invalid' print an error message and exit - the program. - """ - ftype, msg = classify_input_file(filename) - if ftype == IT_Invalid: - print("Invalid input file: %s" % msg) - sys.exit(1) - return ftype - - -def find_benchmark_flag(prefix, benchmark_flags): - """ - Search the specified list of flags for a flag matching `` and - if it is found return the arg it specifies. If specified more than once the - last value is returned. If the flag is not found None is returned. - """ - assert prefix.startswith('--') and prefix.endswith('=') - result = None - for f in benchmark_flags: - if f.startswith(prefix): - result = f[len(prefix):] - return result - - -def remove_benchmark_flags(prefix, benchmark_flags): - """ - Return a new list containing the specified benchmark_flags except those - with the specified prefix. - """ - assert prefix.startswith('--') and prefix.endswith('=') - return [f for f in benchmark_flags if not f.startswith(prefix)] - - -def load_benchmark_results(fname): - """ - Read benchmark output from a file and return the JSON object. - REQUIRES: 'fname' names a file containing JSON benchmark output. - """ - with open(fname, 'r') as f: - return json.load(f) - - -def run_benchmark(exe_name, benchmark_flags): - """ - Run a benchmark specified by 'exe_name' with the specified - 'benchmark_flags'. The benchmark is run directly as a subprocess to preserve - real time console output. - RETURNS: A JSON object representing the benchmark output - """ - output_name = find_benchmark_flag('--benchmark_out=', - benchmark_flags) - is_temp_output = False - if output_name is None: - is_temp_output = True - thandle, output_name = tempfile.mkstemp() - os.close(thandle) - benchmark_flags = list(benchmark_flags) + \ - ['--benchmark_out=%s' % output_name] - - cmd = [exe_name] + benchmark_flags - print("RUNNING: %s" % ' '.join(cmd)) - exitCode = subprocess.call(cmd) - if exitCode != 0: - print('TEST FAILED...') - sys.exit(exitCode) - json_res = load_benchmark_results(output_name) - if is_temp_output: - os.unlink(output_name) - return json_res - - -def run_or_load_benchmark(filename, benchmark_flags): - """ - Get the results for a specified benchmark. If 'filename' specifies - an executable benchmark then the results are generated by running the - benchmark. Otherwise 'filename' must name a valid JSON output file, - which is loaded and the result returned. - """ - ftype = check_input_file(filename) - if ftype == IT_JSON: - return load_benchmark_results(filename) - elif ftype == IT_Executable: - return run_benchmark(filename, benchmark_flags) - else: - assert False # This branch is unreachable diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/strip_asm.py b/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/strip_asm.py deleted file mode 100755 index 9030550b43b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/benchmark/tools/strip_asm.py +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env python - -""" -strip_asm.py - Cleanup ASM output for the specified file -""" - -from argparse import ArgumentParser -import sys -import os -import re - -def find_used_labels(asm): - found = set() - label_re = re.compile("\s*j[a-z]+\s+\.L([a-zA-Z0-9][a-zA-Z0-9_]*)") - for l in asm.splitlines(): - m = label_re.match(l) - if m: - found.add('.L%s' % m.group(1)) - return found - - -def normalize_labels(asm): - decls = set() - label_decl = re.compile("^[.]{0,1}L([a-zA-Z0-9][a-zA-Z0-9_]*)(?=:)") - for l in asm.splitlines(): - m = label_decl.match(l) - if m: - decls.add(m.group(0)) - if len(decls) == 0: - return asm - needs_dot = next(iter(decls))[0] != '.' - if not needs_dot: - return asm - for ld in decls: - asm = re.sub("(^|\s+)" + ld + "(?=:|\s)", '\\1.' + ld, asm) - return asm - - -def transform_labels(asm): - asm = normalize_labels(asm) - used_decls = find_used_labels(asm) - new_asm = '' - label_decl = re.compile("^\.L([a-zA-Z0-9][a-zA-Z0-9_]*)(?=:)") - for l in asm.splitlines(): - m = label_decl.match(l) - if not m or m.group(0) in used_decls: - new_asm += l - new_asm += '\n' - return new_asm - - -def is_identifier(tk): - if len(tk) == 0: - return False - first = tk[0] - if not first.isalpha() and first != '_': - return False - for i in range(1, len(tk)): - c = tk[i] - if not c.isalnum() and c != '_': - return False - return True - -def process_identifiers(l): - """ - process_identifiers - process all identifiers and modify them to have - consistent names across all platforms; specifically across ELF and MachO. - For example, MachO inserts an additional understore at the beginning of - names. This function removes that. - """ - parts = re.split(r'([a-zA-Z0-9_]+)', l) - new_line = '' - for tk in parts: - if is_identifier(tk): - if tk.startswith('__Z'): - tk = tk[1:] - elif tk.startswith('_') and len(tk) > 1 and \ - tk[1].isalpha() and tk[1] != 'Z': - tk = tk[1:] - new_line += tk - return new_line - - -def process_asm(asm): - """ - Strip the ASM of unwanted directives and lines - """ - new_contents = '' - asm = transform_labels(asm) - - # TODO: Add more things we want to remove - discard_regexes = [ - re.compile("\s+\..*$"), # directive - re.compile("\s*#(NO_APP|APP)$"), #inline ASM - re.compile("\s*#.*$"), # comment line - re.compile("\s*\.globa?l\s*([.a-zA-Z_][a-zA-Z0-9$_.]*)"), #global directive - re.compile("\s*\.(string|asciz|ascii|[1248]?byte|short|word|long|quad|value|zero)"), - ] - keep_regexes = [ - - ] - fn_label_def = re.compile("^[a-zA-Z_][a-zA-Z0-9_.]*:") - for l in asm.splitlines(): - # Remove Mach-O attribute - l = l.replace('@GOTPCREL', '') - add_line = True - for reg in discard_regexes: - if reg.match(l) is not None: - add_line = False - break - for reg in keep_regexes: - if reg.match(l) is not None: - add_line = True - break - if add_line: - if fn_label_def.match(l) and len(new_contents) != 0: - new_contents += '\n' - l = process_identifiers(l) - new_contents += l - new_contents += '\n' - return new_contents - -def main(): - parser = ArgumentParser( - description='generate a stripped assembly file') - parser.add_argument( - 'input', metavar='input', type=str, nargs=1, - help='An input assembly file') - parser.add_argument( - 'out', metavar='output', type=str, nargs=1, - help='The output file') - args, unknown_args = parser.parse_known_args() - input = args.input[0] - output = args.out[0] - if not os.path.isfile(input): - print(("ERROR: input file '%s' does not exist") % input) - sys.exit(1) - contents = None - with open(input, 'r') as f: - contents = f.read() - new_contents = process_asm(contents) - with open(output, 'w') as f: - f.write(new_contents) - - -if __name__ == '__main__': - main() - -# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 -# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off; -# kate: indent-mode python; remove-trailing-spaces modified; diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.bazelci/presubmit.yml b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.bazelci/presubmit.yml deleted file mode 100644 index 4a6248dd112..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.bazelci/presubmit.yml +++ /dev/null @@ -1,17 +0,0 @@ ---- -platforms: - ubuntu1604: - build_targets: - - "..." - test_targets: - - "..." - ubuntu1804: - build_targets: - - "..." - test_targets: - - "..." - macos: - build_targets: - - "..." - test_targets: - - "..." diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.gitignore b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.gitignore deleted file mode 100644 index 76d251f6e17..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -autom4te.cache -glog-*.tar.gz -packages/rpm-unknown -packages/debian-* -CMakeCache.txt -CMakeFiles/ -*.cmake -config.h -*.sln -*.vcxproj -*.filters -bazel-* diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.travis.ubuntu.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.travis.ubuntu.sh deleted file mode 100755 index 1043f31ef91..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.travis.ubuntu.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash -set -e -set -x - -uname -a - -cmake -H. -B_build_${TOOLCHAIN} -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/${TOOLCHAIN}.cmake" -cmake --build _build_${TOOLCHAIN} -- -j4 - -if [ "$RUN_TESTS" = true ]; then - case "$TOOLCHAIN" in linux-mingw*) - echo "copy runtime libraries needed for tests into build directory" - cp /usr/x86_64-w64-mingw32/lib/libwinpthread-1.dll /usr/lib/gcc/x86_64-w64-mingw32/7.3-win32/{libstdc++-6.dll,libgcc_s_seh-1.dll} _build_${TOOLCHAIN} - esac - CTEST_OUTPUT_ON_FAILURE=1 cmake --build _build_${TOOLCHAIN} --target test -fi - - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.travis.yml b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.travis.yml deleted file mode 100644 index 911fa5e0e18..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/.travis.yml +++ /dev/null @@ -1,119 +0,0 @@ -sudo: required -language: bash -services: - - docker - -# define the build matrix -env: - global: - - PROJECT_DIR: . - - TOOLCHAIN: gcc-cxx11 - - BUILD_PACKAGES: cmake - - RUN_TESTS: true - -matrix: - include: - # Linux { - - # Ubuntu 14.04 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=trusty - BUILD_ARCH=amd64 - BUILD_PACKAGES=cmake3 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=trusty - BUILD_ARCH=i386 - BUILD_PACKAGES=cmake3 - # Ubuntu 16.04 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=xenial - BUILD_ARCH=amd64 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=xenial - BUILD_ARCH=i386 - # Ubuntu 18.04 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=bionic - BUILD_ARCH=amd64 - TOOLCHAIN=gcc-cxx98 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=bionic - BUILD_ARCH=amd64 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=bionic - BUILD_ARCH=amd64 - TOOLCHAIN=gcc-gnuxx11 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=bionic - BUILD_ARCH=amd64 - TOOLCHAIN=gcc-cxx17 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=bionic - BUILD_ARCH=amd64 - TOOLCHAIN=clang-cxx17 - BUILD_PACKAGES="cmake clang" - # } // end Linux - - # Windows build with mingw-w64 on Ubuntu 18.04 - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=bionic - BUILD_ARCH=amd64 - TOOLCHAIN=linux-mingw-w64-cxx11 - BUILD_PACKAGES="cmake mingw-w64 wine-stable" - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=bionic - BUILD_ARCH=amd64 - TOOLCHAIN=linux-mingw-w64-gnuxx11 - BUILD_PACKAGES="cmake mingw-w64 wine-stable" - - os: linux - env: > - BUILD_FLAVOR=ubuntu - BUILD_RELEASE=bionic - BUILD_ARCH=amd64 - TOOLCHAIN=linux-mingw-w64-cxx17 - BUILD_PACKAGES="cmake mingw-w64 wine-stable" - -before_install: - # use the Dockerfile..template file for building the image with sed magic - - | - sed \ - -e "s/@BUILD_FLAVOR@/${BUILD_FLAVOR}/g" \ - -e "s/@BUILD_RELEASE@/${BUILD_RELEASE}/g" \ - -e "s/@BUILD_ARCH@/${BUILD_ARCH}/g" \ - -e "s/@BUILD_PACKAGES@/${BUILD_PACKAGES}/g" \ - Dockerfile.$BUILD_FLAVOR.template | tee Dockerfile.$BUILD_FLAVOR.$BUILD_RELEASE.$BUILD_ARCH - - docker build -f Dockerfile.$BUILD_FLAVOR.$BUILD_RELEASE.$BUILD_ARCH -t glog-devel . - -script: | - # run the respective .travis..sh script - docker run \ - -e BUILD_FLAVOR="$BUILD_FLAVOR" \ - -e BUILD_RELEASE="$BUILD_RELEASE" \ - -e BUILD_ARCH="$BUILD_ARCH" \ - -e PROJECT_DIR="$PROJECT_DIR" \ - -e TOOLCHAIN="$TOOLCHAIN" \ - -e RUN_TESTS="$RUN_TESTS" \ - -it glog-devel ./.travis.$BUILD_FLAVOR.sh - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/AUTHORS b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/AUTHORS deleted file mode 100644 index e5111cea7dd..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/AUTHORS +++ /dev/null @@ -1,25 +0,0 @@ -# This is the official list of glog authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. -# -# Names should be added to this file as: -# Name or Organization -# The email address is not required for organizations. -# -# Please keep the list sorted. - -Abhishek Dasgupta -Abhishek Parmar -Andrew Schwartzmeyer -Andy Ying -Brian Silverman -Google Inc. -Guillaume Dumont -Michael Tanner -MiniLight -romange -Roman Perepelitsa -Sergiu Deitsch -tbennun -Teddy Reed -Zhongming Qu diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/BUILD b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/BUILD deleted file mode 100644 index 37fb27bb431..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/BUILD +++ /dev/null @@ -1,5 +0,0 @@ -licenses(['notice']) - -load(':bazel/glog.bzl', 'glog_library') - -glog_library() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/CMakeLists.txt b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/CMakeLists.txt deleted file mode 100644 index 808330e2004..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/CMakeLists.txt +++ /dev/null @@ -1,684 +0,0 @@ -cmake_minimum_required (VERSION 3.0) - -if (POLICY CMP0042) - cmake_policy (SET CMP0042 NEW) -endif (POLICY CMP0042) - -if (POLICY CMP0063) - cmake_policy (SET CMP0063 NEW) -endif (POLICY CMP0063) - -project(glog VERSION 0.4.0 LANGUAGES C CXX) - -set (CPACK_PACKAGE_NAME glog) -set (CPACK_PACKAGE_DESCRIPTION_SUMMARY "") -set (CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) -set (CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) -set (CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) -set (CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) - -option (WITH_GFLAGS "Use gflags" ON) -option (WITH_THREADS "Enable multithreading support" ON) -option (WITH_TLS "Enable Thread Local Storage (TLS) support" ON) -option (BUILD_SHARED_LIBS "Build shared libraries" OFF) -option (PRINT_UNSYMBOLIZED_STACK_TRACES - "Print raw pc values on symbolization failure" OFF) - -list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) - -include (CheckCSourceCompiles) -include (CheckCXXCompilerFlag) -include (CheckCXXSourceCompiles) -include (CheckCXXSourceRuns) -include (CheckFunctionExists) -include (CheckIncludeFile) -include (CheckIncludeFileCXX) -include (CheckLibraryExists) -include (CheckStructHasMember) -include (CheckSymbolExists) -include (CheckTypeSize) -include (CMakePackageConfigHelpers) -include (CMakePushCheckState) -include (CPack) -include (CTest) -include (DetermineGflagsNamespace) -include (GNUInstallDirs) - -set (CMAKE_DEBUG_POSTFIX d) -set (CMAKE_THREAD_PREFER_PTHREAD 1) - -if (WITH_GFLAGS) - find_package (gflags 2.2.0) - - if (gflags_FOUND) - set (HAVE_LIB_GFLAGS 1) - determine_gflags_namespace (gflags_NAMESPACE) - endif (gflags_FOUND) -endif (WITH_GFLAGS) - -if (WITH_THREADS) - find_package (Threads) -endif (WITH_THREADS) - -check_include_file (dlfcn.h HAVE_DLFCN_H) -check_include_file (execinfo.h HAVE_EXECINFO_H) -check_include_file (glob.h HAVE_GLOB_H) -check_include_file (inttypes.h HAVE_INTTYPES_H) -check_include_file (libunwind.h HAVE_LIBUNWIND_H) -check_include_file (memory.h HAVE_MEMORY_H) -check_include_file (pwd.h HAVE_PWD_H) -check_include_file (stdint.h HAVE_STDINT_H) -check_include_file (stdlib.h HAVE_STDLIB_H) -check_include_file (string.h HAVE_STRING_H) -check_include_file (strings.h HAVE_STRINGS_H) -check_include_file (sys/stat.h HAVE_SYS_STAT_H) -check_include_file (sys/syscall.h HAVE_SYS_SYSCALL_H) -check_include_file (sys/time.h HAVE_SYS_TIME_H) -check_include_file (sys/types.h HAVE_SYS_TYPES_H) -check_include_file (sys/utsname.h HAVE_SYS_UTSNAME_H) -check_include_file (syscall.h HAVE_SYSCALL_H) -check_include_file (syslog.h HAVE_SYSLOG_H) -check_include_file (ucontext.h HAVE_UCONTEXT_H) -check_include_file (unistd.h HAVE_UNISTD_H) -check_include_file (unwind.h HAVE_UNWIND_H) -check_include_file (pwd.h HAVE_PWD_H) - -check_include_file_cxx ("ext/hash_map" HAVE_EXT_HASH_MAP) -check_include_file_cxx ("ext/hash_set" HAVE_EXT_HASH_SET) -check_include_file_cxx ("ext/slist" HAVE_EXT_SLIST) -check_include_file_cxx ("tr1/unordered_map" HAVE_TR1_UNORDERED_MAP) -check_include_file_cxx ("tr1/unordered_set" HAVE_TR1_UNORDERED_SET) -check_include_file_cxx ("unordered_map" HAVE_UNORDERED_MAP) -check_include_file_cxx ("unordered_set" HAVE_UNORDERED_SET) - -check_type_size ("unsigned __int16" HAVE___UINT16) -check_type_size (u_int16_t HAVE_U_INT16_T) -check_type_size (uint16_t HAVE_UINT16_T) - -check_function_exists (dladdr HAVE_DLADDR) -check_function_exists (fcntl HAVE_FCNTL) -check_function_exists (pread HAVE_PREAD) -check_function_exists (pwrite HAVE_PWRITE) -check_function_exists (sigaction HAVE_SIGACTION) -check_function_exists (sigaltstack HAVE_SIGALSTACK) - -# NOTE gcc does not fail if you pass a non-existent -Wno-* option as an -# argument. However, it will happily fail if you pass the corresponding -W* -# option. So, we check whether options that disable warnings exist by testing -# the availability of the corresponding option that enables the warning. This -# eliminates the need to check for compiler for several (mainly Clang) options. - -check_cxx_compiler_flag (-Wdeprecated HAVE_NO_DEPRECATED) -check_cxx_compiler_flag (-Wunnamed-type-template-args - HAVE_NO_UNNAMED_TYPE_TEMPLATE_ARGS) - -# NOTE: Cannot use check_function_exists here since >=vc-14.0 can define -# snprintf as an inline function -check_symbol_exists (snprintf stdio.h HAVE_SNPRINTF) - -check_library_exists (unwind get_static_proc_name "" HAVE_LIB_UNWIND) -check_library_exists (dbghelp UnDecorateSymbolName "" HAVE_DBGHELP) - -find_library (UNWIND_LIBRARY NAMES unwind DOC "unwind library") -mark_as_advanced (UNWIND_LIBRARY) - -check_c_source_compiles (" -#include -static void foo(void) __attribute__ ((unused)); -int main(void) { return 0; } -" HAVE___ATTRIBUTE__) - -check_c_source_compiles (" -#include -static void foo(void) __attribute__ ((visibility(\"default\"))); -int main(void) { return 0; } -" HAVE___ATTRIBUTE__VISIBILITY_DEFAULT) - -check_c_source_compiles (" -#include -static void foo(void) __attribute__ ((visibility(\"hidden\"))); -int main(void) { return 0; } -" HAVE___ATTRIBUTE__VISIBILITY_HIDDEN) - -check_c_source_compiles (" -int main(void) { if (__builtin_expect(0, 0)) return 1; return 0; } -" HAVE___BUILTIN_EXPECT) - -check_c_source_compiles (" -int main(void) -{ - int a; if (__sync_val_compare_and_swap(&a, 0, 1)) return 1; return 0; -} -" HAVE___SYNC_VAL_COMPARE_AND_SWAP) - -check_c_source_compiles (" -#define _XOPEN_SOURCE 500 -#include -int main(void) -{ - pthread_rwlock_t l; - pthread_rwlock_init(&l, NULL); - pthread_rwlock_rdlock(&l); - return 0; -} -" HAVE_RWLOCK) - -check_c_source_compiles (" -__declspec(selectany) int a; -int main(void) { return 0; } -" HAVE___DECLSPEC) - -check_cxx_source_compiles (" -#include -vector t; int main() { } -" STL_NO_NAMESPACE) - -check_cxx_source_compiles (" -#include -std::vector t; int main() { } -" STL_STD_NAMESPACE) - -check_cxx_source_compiles (" -#include -std::ostream& operator<<(std::ostream&, struct s); -using ::operator<<; -int main() { } -" HAVE_USING_OPERATOR) - -check_cxx_source_compiles (" -namespace Outer { namespace Inner { int i = 0; }} -using namespace Outer::Inner;; -int main() { return i; } -" HAVE_NAMESPACES) - -check_cxx_source_compiles (" -__thread int tls; -int main() { } -" HAVE_GCC_TLS) - -check_cxx_source_compiles (" -__declspec(thread) int tls; -int main() { } -" HAVE_MSVC_TLS) - -check_cxx_source_compiles (" -thread_local int tls; -int main() { } -" HAVE_CXX11_TLS) - -check_cxx_source_compiles (" -#include -std::aligned_storage::type data; -int main() { } -" HAVE_ALIGNED_STORAGE) - -if (WITH_TLS) - # Cygwin does not support the thread attribute. Don't bother. - if (HAVE_GCC_TLS) - set (GLOG_THREAD_LOCAL_STORAGE "__thread") - elseif (HAVE_MSVC_TLS) - set (GLOG_THREAD_LOCAL_STORAGE "__declspec(thread)") - elseif (HAVE_CXX11_TLS) - set (GLOG_THREAD_LOCAL_STORAGE thread_local) - endif (HAVE_GCC_TLS) -endif (WITH_TLS) - -set (_PC_FIELDS - "gregs[REG_PC]" - "gregs[REG_EIP]" - "gregs[REG_RIP]" - "sc_ip" - "uc_regs->gregs[PT_NIP]" - "gregs[R15]" - "arm_pc" - "mc_eip" - "mc_rip" - "__gregs[REG_EIP]" - "__gregs[REG_RIP]" - "ss.eip" - "__ss.__eip" - "ss.rip" - "__ss.__rip" - "ss.srr0" - "__ss.__srr0" -) - -set (_PC_HEADERS ucontext.h signal.h) - -if (HAVE_UCONTEXT_H AND NOT PC_FROM_UCONTEXT) - foreach (_PC_FIELD ${_PC_FIELDS}) - foreach (_PC_HEADER ${_PC_HEADERS}) - set (_TMP - ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/uctfield.c) - file (WRITE ${_TMP} " -#define _GNU_SOURCE 1 -#include <${_PC_HEADER}> -int main(void) -{ - ucontext_t u; - return u.${_PC_FIELD} == 0; -} -") - try_compile (HAVE_PC_FROM_UCONTEXT ${CMAKE_CURRENT_BINARY_DIR} ${_TMP} - COMPILE_DEFINITIONS _GNU_SOURCE=1) - - if (HAVE_PC_FROM_UCONTEXT) - set (PC_FROM_UCONTEXT ${_PC_FIELD} CACHE) - endif (HAVE_PC_FROM_UCONTEXT) - endforeach (_PC_HEADER) - endforeach (_PC_FIELD) -endif (HAVE_UCONTEXT_H AND NOT PC_FROM_UCONTEXT) - -if (STL_STD_NAMESPACE) - set (STL_NAMESPACE std) -else (STL_STD_NAMESPACE) - set (STL_NAMESPACE "") -endif (STL_STD_NAMESPACE) - -set (GOOGLE_NAMESPACE google) -set (_START_GOOGLE_NAMESPACE_ "namespace ${GOOGLE_NAMESPACE} {") -set (_END_GOOGLE_NAMESPACE_ "}") - -if (HAVE___UINT16) - set (ac_cv_have___uint16 1) -else (HAVE___UINT16) - set (ac_cv_have___uint16 0) -endif (HAVE___UINT16) - -if (HAVE_INTTYPES_H) - set (ac_cv_have_inttypes_h 1) -else (HAVE_INTTYPES_H) - set (ac_cv_have_inttypes_h 0) -endif (HAVE_INTTYPES_H) - -if (HAVE_LIB_GFLAGS) - set (ac_cv_have_libgflags 1) -else (HAVE_LIB_GFLAGS) - set (ac_cv_have_libgflags 0) -endif (HAVE_LIB_GFLAGS) - -if (HAVE_STDINT_H) - set (ac_cv_have_stdint_h 1) -else (HAVE_STDINT_H) - set (ac_cv_have_stdint_h 0) -endif (HAVE_STDINT_H) - -if (HAVE_SYS_TYPES_H) - set (ac_cv_have_systypes_h 1) -else (HAVE_SYS_TYPES_H) - set (ac_cv_have_systypes_h 0) -endif (HAVE_SYS_TYPES_H) - -if (HAVE_U_INT16_T) - set (ac_cv_have_u_int16_t 1) -else (HAVE_U_INT16_T) - set (ac_cv_have_u_int16_t 0) -endif (HAVE_U_INT16_T) - -if (HAVE_UINT16_T) - set (ac_cv_have_uint16_t 1) -else (HAVE_UINT16_T) - set (ac_cv_have_uint16_t 0) -endif (HAVE_UINT16_T) - -if (HAVE_UNISTD_H) - set (ac_cv_have_unistd_h 1) -else (HAVE_UNISTD_H) - set (ac_cv_have_unistd_h 0) -endif (HAVE_UNISTD_H) - -set (ac_google_namespace ${GOOGLE_NAMESPACE}) -set (ac_google_end_namespace ${_END_GOOGLE_NAMESPACE_}) -set (ac_google_start_namespace ${_START_GOOGLE_NAMESPACE_}) - -if (HAVE___ATTRIBUTE__) - set (ac_cv___attribute___noreturn "__attribute__((noreturn))") - set (ac_cv___attribute___noinline "__attribute__((noinline))") -elseif (HAVE___DECLSPEC) - set (ac_cv___attribute___noreturn "__declspec(noreturn)") - #set (ac_cv___attribute___noinline "__declspec(noinline)") -endif (HAVE___ATTRIBUTE__) - -if (HAVE___BUILTIN_EXPECT) - set (ac_cv_have___builtin_expect 1) -else (HAVE___BUILTIN_EXPECT) - set (ac_cv_have___builtin_expect 0) -endif (HAVE___BUILTIN_EXPECT) - -if (HAVE_USING_OPERATOR) - set (ac_cv_cxx_using_operator 1) -else (HAVE_USING_OPERATOR) - set (ac_cv_cxx_using_operator 0) -endif (HAVE_USING_OPERATOR) - -if (HAVE_EXECINFO_H) - set (HAVE_STACKTRACE 1) -endif (HAVE_EXECINFO_H) - -if (WIN32 OR CYGWIN) - cmake_push_check_state (RESET) - set (CMAKE_REQUIRED_LIBRARIES DbgHelp) - - check_cxx_source_runs ([=[ - #include - #include - #include - - void foobar() { } - - int main() - { - HANDLE process = GetCurrentProcess(); - - if (!SymInitialize(process, NULL, TRUE)) - return EXIT_FAILURE; - - char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; - SYMBOL_INFO *symbol = reinterpret_cast(buf); - symbol->SizeOfStruct = sizeof(SYMBOL_INFO); - symbol->MaxNameLen = MAX_SYM_NAME; - - void* const pc = reinterpret_cast(&foobar); - BOOL ret = SymFromAddr(process, reinterpret_cast(pc), 0, symbol); - - return ret ? EXIT_SUCCESS : EXIT_FAILURE; - } - ]=] HAVE_SYMBOLIZE) - - cmake_pop_check_state () - - if (HAVE_SYMBOLIZE) - set (HAVE_STACKTRACE 1) - endif (HAVE_SYMBOLIZE) -elseif (UNIX OR (APPLE AND HAVE_DLADDR)) - set (HAVE_SYMBOLIZE 1) -endif (WIN32 OR CYGWIN) - -check_cxx_source_compiles (" -#include -#include -int main() -{ - time_t timep; - struct tm result; - localtime_r(&timep, &result); - return EXIT_SUCCESS; -} -" HAVE_LOCALTIME_R) - -set (SIZEOF_VOID_P ${CMAKE_SIZEOF_VOID_P}) - -if (WITH_THREADS AND Threads_FOUND) - if (CMAKE_USE_PTHREADS_INIT) - set (HAVE_PTHREAD 1) - endif (CMAKE_USE_PTHREADS_INIT) -else (WITH_THREADS AND Threads_FOUND) - set (NO_THREADS 1) -endif (WITH_THREADS AND Threads_FOUND) - -set (TEST_SRC_DIR \"${CMAKE_CURRENT_SOURCE_DIR}\") - -configure_file (src/config.h.cmake.in config.h) -configure_file (src/glog/logging.h.in glog/logging.h @ONLY) -configure_file (src/glog/raw_logging.h.in glog/raw_logging.h @ONLY) -configure_file (src/glog/stl_logging.h.in glog/stl_logging.h @ONLY) -configure_file (src/glog/vlog_is_on.h.in glog/vlog_is_on.h @ONLY) - -set (CMAKE_CXX_VISIBILITY_PRESET default) -set (CMAKE_VISIBILITY_INLINES_HIDDEN 1) - -set (GLOG_PUBLIC_H - ${CMAKE_CURRENT_BINARY_DIR}/glog/logging.h - ${CMAKE_CURRENT_BINARY_DIR}/glog/raw_logging.h - ${CMAKE_CURRENT_BINARY_DIR}/glog/stl_logging.h - ${CMAKE_CURRENT_BINARY_DIR}/glog/vlog_is_on.h - src/glog/log_severity.h -) - -set (GLOG_SRCS - ${GLOG_PUBLIC_H} - src/base/commandlineflags.h - src/base/googleinit.h - src/base/mutex.h - src/demangle.cc - src/demangle.h - src/logging.cc - src/raw_logging.cc - src/symbolize.cc - src/symbolize.h - src/utilities.cc - src/utilities.h - src/vlog_is_on.cc -) - -if (HAVE_PTHREAD OR WIN32) - list (APPEND GLOG_SRCS src/signalhandler.cc) -endif (HAVE_PTHREAD OR WIN32) - -if (WIN32) - list (APPEND GLOG_SRCS - src/windows/port.cc - src/windows/port.h - ) -endif (WIN32) - -add_compile_options ($<$,$>>:-Wno-unnamed-type-template-args>) - -add_library (glog - ${GLOG_SRCS} -) -add_library(glog::glog ALIAS glog) - -set_target_properties (glog PROPERTIES POSITION_INDEPENDENT_CODE ON) - -if (UNWIND_LIBRARY) - target_link_libraries (glog PUBLIC ${UNWIND_LIBRARY}) -endif (UNWIND_LIBRARY) - -if (HAVE_DBGHELP) - target_link_libraries (glog PUBLIC dbghelp) -endif (HAVE_DBGHELP) - -if (HAVE_PTHREAD) - target_link_libraries (glog PUBLIC ${CMAKE_THREAD_LIBS_INIT}) -endif (HAVE_PTHREAD) - -if (WIN32 AND HAVE_SNPRINTF) - set_property (SOURCE src/windows/port.cc APPEND PROPERTY COMPILE_DEFINITIONS - HAVE_SNPRINTF) -endif (WIN32 AND HAVE_SNPRINTF) - -if (gflags_FOUND) - target_link_libraries (glog PUBLIC gflags) - - if (NOT BUILD_SHARED_LIBS) - # Don't use __declspec(dllexport|dllimport) if this is a static build - targeT_compile_definitions (glog PUBLIC GFLAGS_DLL_DECLARE_FLAG= GFLAGS_DLL_DEFINE_FLAG=) - endif (NOT BUILD_SHARED_LIBS) -endif (gflags_FOUND) - -set_target_properties (glog PROPERTIES VERSION ${PROJECT_VERSION}) -set_target_properties (glog PROPERTIES SOVERSION ${PROJECT_VERSION_MAJOR}) - -if (WIN32) - target_compile_definitions (glog PUBLIC GLOG_NO_ABBREVIATED_SEVERITIES) -endif (WIN32) - -set_target_properties (glog PROPERTIES PUBLIC_HEADER "${GLOG_PUBLIC_H}") - -set (_glog_CMake_BINDIR ${CMAKE_INSTALL_BINDIR}) -set (_glog_CMake_INCLUDE_DIR ${CMAKE_INSTALL_INCLUDEDIR}) -set (_glog_CMake_LIBDIR ${CMAKE_INSTALL_LIBDIR}) -set (_glog_CMake_INSTALLDIR ${_glog_CMake_LIBDIR}/cmake/glog) - -target_include_directories (glog BEFORE PUBLIC - "$" - "$" - "$" - PRIVATE ${CMAKE_CURRENT_BINARY_DIR} - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - -if (WIN32) - target_include_directories (glog PUBLIC - "$" - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/windows) -endif (WIN32) - -set_target_properties (glog PROPERTIES DEFINE_SYMBOL LIBGLOG_EXPORTS) - -if (NOT BUILD_SHARED_LIBS) - target_compile_definitions (glog PUBLIC GOOGLE_GLOG_DLL_DECL=) -else (NOT BUILD_SHARED_LIBS) - target_compile_definitions (glog PRIVATE GOOGLE_GLOG_IS_A_DLL=1) - - if (HAVE___ATTRIBUTE__VISIBILITY_DEFAULT) - set (_EXPORT "__attribute__((visibility(\"default\")))") - set (_IMPORT "") - elseif (HAVE___DECLSPEC) - set (_EXPORT "__declspec(dllexport)") - set (_IMPORT "__declspec(dllimport)") - endif (HAVE___ATTRIBUTE__VISIBILITY_DEFAULT) - - target_compile_definitions (glog PRIVATE - "GOOGLE_GLOG_DLL_DECL=${_EXPORT}") - target_compile_definitions (glog INTERFACE - "GOOGLE_GLOG_DLL_DECL=${_IMPORT}") - target_compile_definitions (glog INTERFACE - "GOOGLE_GLOG_DLL_DECL_FOR_UNITTESTS=${_IMPORT}") -endif (NOT BUILD_SHARED_LIBS) - -# Unit testing - -if (BUILD_TESTING) - add_executable (logging_unittest - src/logging_unittest.cc - ) - - target_link_libraries (logging_unittest PRIVATE glog) - - add_executable (stl_logging_unittest - src/stl_logging_unittest.cc - ) - - target_link_libraries (stl_logging_unittest PRIVATE glog) - - if (HAVE_NO_DEPRECATED) - set_property (TARGET stl_logging_unittest APPEND PROPERTY COMPILE_OPTIONS - -Wno-deprecated) - endif (HAVE_NO_DEPRECATED) - - if (HAVE_UNORDERED_MAP AND HAVE_UNORDERED_SET) - target_compile_definitions (stl_logging_unittest PRIVATE - GLOG_STL_LOGGING_FOR_UNORDERED) - endif (HAVE_UNORDERED_MAP AND HAVE_UNORDERED_SET) - - if (HAVE_TR1_UNORDERED_MAP AND HAVE_TR1_UNORDERED_SET) - target_compile_definitions (stl_logging_unittest PRIVATE - GLOG_STL_LOGGING_FOR_TR1_UNORDERED) - endif (HAVE_TR1_UNORDERED_MAP AND HAVE_TR1_UNORDERED_SET) - - if (HAVE_EXT_HASH_MAP AND HAVE_EXT_HASH_SET) - target_compile_definitions (stl_logging_unittest PRIVATE - GLOG_STL_LOGGING_FOR_EXT_HASH) - endif (HAVE_EXT_HASH_MAP AND HAVE_EXT_HASH_SET) - - if (HAVE_EXT_SLIST) - target_compile_definitions (stl_logging_unittest PRIVATE - GLOG_STL_LOGGING_FOR_EXT_SLIST) - endif (HAVE_EXT_SLIST) - - if (HAVE_SYMBOLIZE) - add_executable (symbolize_unittest - src/symbolize_unittest.cc - ) - - target_link_libraries (symbolize_unittest PRIVATE glog) - endif (HAVE_SYMBOLIZE) - - add_executable (demangle_unittest - src/demangle_unittest.cc - ) - - target_link_libraries (demangle_unittest PRIVATE glog) - - if (HAVE_STACKTRACE) - add_executable (stacktrace_unittest - src/stacktrace_unittest.cc - ) - - target_link_libraries (stacktrace_unittest PRIVATE glog) - endif (HAVE_STACKTRACE) - - add_executable (utilities_unittest - src/utilities_unittest.cc - ) - - target_link_libraries (utilities_unittest PRIVATE glog) - - if (HAVE_STACKTRACE AND HAVE_SYMBOLIZE) - add_executable (signalhandler_unittest - src/signalhandler_unittest.cc - ) - - target_link_libraries (signalhandler_unittest PRIVATE glog) - endif (HAVE_STACKTRACE AND HAVE_SYMBOLIZE) - - add_test (NAME demangle COMMAND demangle_unittest) - add_test (NAME logging COMMAND logging_unittest) - - if (TARGET signalhandler_unittest) - add_test (NAME signalhandler COMMAND signalhandler_unittest) - endif (TARGET signalhandler_unittest) - - if (TARGET stacktrace_unittest) - add_test (NAME stacktrace COMMAND stacktrace_unittest) - set_tests_properties(stacktrace PROPERTIES TIMEOUT 30) - endif (TARGET stacktrace_unittest) - - add_test (NAME stl_logging COMMAND stl_logging_unittest) - - if (TARGET symbolize_unittest) - add_test (NAME symbolize COMMAND symbolize_unittest) - endif (TARGET symbolize_unittest) -endif (BUILD_TESTING) - -install (TARGETS glog - EXPORT glog-targets - RUNTIME DESTINATION ${_glog_CMake_BINDIR} - PUBLIC_HEADER DESTINATION ${_glog_CMake_INCLUDE_DIR}/glog - LIBRARY DESTINATION ${_glog_CMake_LIBDIR} - ARCHIVE DESTINATION ${_glog_CMake_LIBDIR}) - -set (glog_CMake_VERSION 3.0) - -if (gflags_FOUND) - # Ensure clients locate only the package config and not third party find - # modules having the same name. This avoid cmake_policy PUSH/POP errors. - if (CMAKE_VERSION VERSION_LESS 3.9) - set (gflags_DEPENDENCY "find_dependency (gflags ${gflags_VERSION})") - else (CMAKE_VERSION VERSION_LESS 3.9) - # Passing additional find_package arguments to find_dependency is possible - # starting with CMake 3.9. - set (glog_CMake_VERSION 3.9) - set (gflags_DEPENDENCY "find_dependency (gflags ${gflags_VERSION} NO_MODULE)") - endif (CMAKE_VERSION VERSION_LESS 3.9) -endif (gflags_FOUND) - -configure_package_config_file (glog-config.cmake.in - ${CMAKE_CURRENT_BINARY_DIR}/glog-config.cmake - INSTALL_DESTINATION ${_glog_CMake_INSTALLDIR} - NO_CHECK_REQUIRED_COMPONENTS_MACRO) - -write_basic_package_version_file (glog-config-version.cmake VERSION - ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion) - -export (TARGETS glog NAMESPACE glog:: FILE glog-targets.cmake) -export (PACKAGE glog) - -install (FILES - ${CMAKE_CURRENT_BINARY_DIR}/glog-config.cmake - ${CMAKE_CURRENT_BINARY_DIR}/glog-config-version.cmake - DESTINATION ${_glog_CMake_INSTALLDIR}) - -install (EXPORT glog-targets NAMESPACE glog:: DESTINATION - ${_glog_CMake_INSTALLDIR}) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/CONTRIBUTING.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/CONTRIBUTING.md deleted file mode 100644 index 43de4c9d470..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/CONTRIBUTING.md +++ /dev/null @@ -1,58 +0,0 @@ -# How to contribute # - -We'd love to accept your patches and contributions to this project. There are -a just a few small guidelines you need to follow. - - -## Contributor License Agreement ## - -Contributions to any Google project must be accompanied by a Contributor -License Agreement. This is not a copyright **assignment**, it simply gives -Google permission to use and redistribute your contributions as part of the -project. - - * If you are an individual writing original source code and you're sure you - own the intellectual property, then you'll need to sign an [individual - CLA][]. - - * If you work for a company that wants to allow you to contribute your work, - then you'll need to sign a [corporate CLA][]. - -You generally only need to submit a CLA once, so if you've already submitted -one (even if it was for a different project), you probably don't need to do it -again. - -[individual CLA]: https://developers.google.com/open-source/cla/individual -[corporate CLA]: https://developers.google.com/open-source/cla/corporate - -Once your CLA is submitted (or if you already submitted one for -another Google project), make a commit adding yourself to the -[AUTHORS][] and [CONTRIBUTORS][] files. This commit can be part -of your first [pull request][]. - -[AUTHORS]: AUTHORS -[CONTRIBUTORS]: CONTRIBUTORS - - -## Submitting a patch ## - - 1. It's generally best to start by opening a new issue describing the bug or - feature you're intending to fix. Even if you think it's relatively minor, - it's helpful to know what people are working on. Mention in the initial - issue that you are planning to work on that bug or feature so that it can - be assigned to you. - - 1. Follow the normal process of [forking][] the project, and setup a new - branch to work in. It's important that each group of changes be done in - separate branches in order to ensure that a pull request only includes the - commits related to that bug or feature. - - 1. Do your best to have [well-formed commit messages][] for each change. - This provides consistency throughout the project, and ensures that commit - messages are able to be formatted properly by various git tools. - - 1. Finally, push the commits to your fork and submit a [pull request][]. - -[forking]: https://help.github.com/articles/fork-a-repo -[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html -[pull request]: https://help.github.com/articles/creating-a-pull-request diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/CONTRIBUTORS b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/CONTRIBUTORS deleted file mode 100644 index d63f62d16e7..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/CONTRIBUTORS +++ /dev/null @@ -1,45 +0,0 @@ -# People who have agreed to one of the CLAs and can contribute patches. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# https://developers.google.com/open-source/cla/individual -# https://developers.google.com/open-source/cla/corporate -# -# The agreement for individuals can be filled out on the web. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. -# -# Names should be added to this file as: -# Name -# -# Please keep the list sorted. - -Abhishek Dasgupta -Abhishek Parmar -Andrew Schwartzmeyer -Andy Ying -Brian Silverman -Fumitoshi Ukai -Guillaume Dumont -Håkan L. S. Younes -Ivan Penkov -Jim Ray -Michael Tanner -MiniLight -Peter Collingbourne -Rodrigo Queiro -romange -Roman Perepelitsa -Sergiu Deitsch -Shinichiro Hamaji -tbennun -Teddy Reed -Zhongming Qu diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/COPYING b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/COPYING deleted file mode 100644 index 38396b580b3..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/COPYING +++ /dev/null @@ -1,65 +0,0 @@ -Copyright (c) 2008, Google Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -A function gettimeofday in utilities.cc is based on - -http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/COPYING&q=GetSystemTimeAsFileTime%20license:bsd - -The license of this code is: - -Copyright (c) 2003-2008, Jouni Malinen and contributors -All Rights Reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -3. Neither the name(s) of the above-listed copyright holder(s) 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. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/ChangeLog b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/ChangeLog deleted file mode 100644 index f8e43f8b39d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/ChangeLog +++ /dev/null @@ -1,99 +0,0 @@ -2019-01-22 Google Inc. - - * google-glog: version 0.4.0. - * See git log for the details. - -2017-05-09 Google Inc. - - * google-glog: version 0.3.5 - * See git log for the details. - -2015-03-09 Google Inc. - - * google-glog: version 0.3.4 - * See git log for the details. - -2013-02-01 Google Inc. - - * google-glog: version 0.3.3 - * Add --disable-rtti option for configure. - * Visual Studio build and test fix. - * QNX build fix (thanks vanuan). - * Reduce warnings. - * Fixed LOG_SYSRESULT (thanks ukai). - * FreeBSD build fix (thanks yyanagisawa). - * Clang build fix. - * Now users can re-initialize glog after ShutdownGoogleLogging. - * Color output support by GLOG_colorlogtostderr (thanks alexs). - * Now glog's ABI around flags are compatible with gflags. - * Document mentions how to modify flags from user programs. - -2012-01-12 Google Inc. - - * google-glog: version 0.3.2 - * Clang support. - * Demangler and stacktrace improvement for newer GCCs. - * Now fork(2) doesn't mess up log files. - * Make valgrind happier. - * Reduce warnings for more -W options. - * Provide a workaround for ERROR defined by windows.h. - -2010-06-15 Google Inc. - - * google-glog: version 0.3.1 - * GLOG_* environment variables now work even when gflags is installed. - * Snow leopard support. - * Now we can build and test from out side tree. - * Add DCHECK_NOTNULL. - * Add ShutdownGoogleLogging to close syslog (thanks DGunchev) - * Fix --enable-frame-pointers option (thanks kazuki.ohta) - * Fix libunwind detection (thanks giantchen) - -2009-07-30 Google Inc. - - * google-glog: version 0.3.0 - * Fix a deadlock happened when user uses glog with recent gflags. - * Suppress several unnecessary warnings (thanks keir). - * NetBSD and OpenBSD support. - * Use Win32API GetComputeNameA properly (thanks magila). - * Fix user name detection for Windows (thanks ademin). - * Fix several minor bugs. - -2009-04-10 Google Inc. - * google-glog: version 0.2.1 - * Fix timestamps of VC++ version. - * Add pkg-config support (thanks Tomasz) - * Fix build problem when building with gtest (thanks Michael) - * Add --with-gflags option for configure (thanks Michael) - * Fixes for GCC 4.4 (thanks John) - -2009-01-23 Google Inc. - * google-glog: version 0.2 - * Add initial Windows VC++ support. - * Google testing/mocking frameworks integration. - * Link pthread library automatically. - * Flush logs in signal handlers. - * Add macros LOG_TO_STRING, LOG_AT_LEVEL, DVLOG, and LOG_TO_SINK_ONLY. - * Log microseconds. - * Add --log_backtrace_at option. - * Fix some minor bugs. - -2008-11-18 Google Inc. - * google-glog: version 0.1.2 - * Add InstallFailureSignalHandler(). (satorux) - * Re-organize the way to produce stacktraces. - * Don't define unnecessary macro DISALLOW_EVIL_CONSTRUCTORS. - -2008-10-15 Google Inc. - * google-glog: version 0.1.1 - * Support symbolize for MacOSX 10.5. - * BUG FIX: --vmodule didn't work with gflags. - * BUG FIX: symbolize_unittest failed with GCC 4.3. - * Several fixes on the document. - -2008-10-07 Google Inc. - - * google-glog: initial release: - The glog package contains a library that implements application-level - logging. This library provides logging APIs based on C++-style - streams and various helper macros. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/Dockerfile.ubuntu.template b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/Dockerfile.ubuntu.template deleted file mode 100644 index 14f9b958917..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/Dockerfile.ubuntu.template +++ /dev/null @@ -1,14 +0,0 @@ -# Build Ubuntu image -FROM @BUILD_ARCH@/@BUILD_FLAVOR@:@BUILD_RELEASE@ - -# see https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#/run -RUN apt-get update && \ - apt-get install -y --no-install-recommends \ - @BUILD_PACKAGES@ \ - build-essential \ - g++ - -RUN mkdir -p /usr/src/app -WORKDIR /usr/src/app - -COPY . /usr/src/app diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/INSTALL b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/INSTALL deleted file mode 100644 index 0f3b55d7207..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/INSTALL +++ /dev/null @@ -1,297 +0,0 @@ -Installation Instructions -************************* - -Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005, -2006, 2007 Free Software Foundation, Inc. - -This file is free documentation; the Free Software Foundation gives -unlimited permission to copy, distribute and modify it. - -Glog-Specific Install Notes -================================ - -*** NOTE FOR 64-BIT LINUX SYSTEMS - -The glibc built-in stack-unwinder on 64-bit systems has some problems -with the glog libraries. (In particular, if you are using -InstallFailureSignalHandler(), the signal may be raised in the middle -of malloc, holding some malloc-related locks when they invoke the -stack unwinder. The built-in stack unwinder may call malloc -recursively, which may require the thread to acquire a lock it already -holds: deadlock.) - -For that reason, if you use a 64-bit system and you need -InstallFailureSignalHandler(), we strongly recommend you install -libunwind before trying to configure or install google glog. -libunwind can be found at - - http://download.savannah.nongnu.org/releases/libunwind/libunwind-snap-070410.tar.gz - -Even if you already have libunwind installed, you will probably still -need to install from the snapshot to get the latest version. - -CAUTION: if you install libunwind from the URL above, be aware that -you may have trouble if you try to statically link your binary with -glog: that is, if you link with 'gcc -static -lgcc_eh ...'. This -is because both libunwind and libgcc implement the same C++ exception -handling APIs, but they implement them differently on some platforms. -This is not likely to be a problem on ia64, but may be on x86-64. - -Also, if you link binaries statically, make sure that you add --Wl,--eh-frame-hdr to your linker options. This is required so that -libunwind can find the information generated by the compiler required -for stack unwinding. - -Using -static is rare, though, so unless you know this will affect you -it probably won't. - -If you cannot or do not wish to install libunwind, you can still try -to use two kinds of stack-unwinder: 1. glibc built-in stack-unwinder -and 2. frame pointer based stack-unwinder. - -1. As we already mentioned, glibc's unwinder has a deadlock issue. -However, if you don't use InstallFailureSignalHandler() or you don't -worry about the rare possibilities of deadlocks, you can use this -stack-unwinder. If you specify no options and libunwind isn't -detected on your system, the configure script chooses this unwinder by -default. - -2. The frame pointer based stack unwinder requires that your -application, the glog library, and system libraries like libc, all be -compiled with a frame pointer. This is *not* the default for x86-64. - -If you are on x86-64 system, know that you have a set of system -libraries with frame-pointers enabled, and compile all your -applications with -fno-omit-frame-pointer, then you can enable the -frame pointer based stack unwinder by passing the ---enable-frame-pointers flag to configure. - - -Basic Installation -================== - -Briefly, the shell commands `./configure; make; make install' should -configure, build, and install this package. The following -more-detailed instructions are generic; see the `README.md' file for -instructions specific to this package. - - The `configure' shell script attempts to guess correct values for -various system-dependent variables used during compilation. It uses -those values to create a `Makefile' in each directory of the package. -It may also create one or more `.h' files containing system-dependent -definitions. Finally, it creates a shell script `config.status' that -you can run in the future to recreate the current configuration, and a -file `config.log' containing compiler output (useful mainly for -debugging `configure'). - - It can also use an optional file (typically called `config.cache' -and enabled with `--cache-file=config.cache' or simply `-C') that saves -the results of its tests to speed up reconfiguring. Caching is -disabled by default to prevent problems with accidental use of stale -cache files. - - If you need to do unusual things to compile the package, please try -to figure out how `configure' could check whether to do them, and mail -diffs or instructions to the address given in the `README.md' so they can -be considered for the next release. If you are using the cache, and at -some point `config.cache' contains results you don't want to keep, you -may remove or edit it. - - The file `configure.ac' (or `configure.in') is used to create -`configure' by a program called `autoconf'. You need `configure.ac' if -you want to change it or regenerate `configure' using a newer version -of `autoconf'. - -The simplest way to compile this package is: - - 1. `cd' to the directory containing the package's source code and type - `./configure' to configure the package for your system. - - Running `configure' might take a while. While running, it prints - some messages telling which features it is checking for. - - 2. Type `make' to compile the package. - - 3. Optionally, type `make check' to run any self-tests that come with - the package. - - 4. Type `make install' to install the programs and any data files and - documentation. - - 5. You can remove the program binaries and object files from the - source code directory by typing `make clean'. To also remove the - files that `configure' created (so you can compile the package for - a different kind of computer), type `make distclean'. There is - also a `make maintainer-clean' target, but that is intended mainly - for the package's developers. If you use it, you may have to get - all sorts of other programs in order to regenerate files that came - with the distribution. - - 6. Often, you can also type `make uninstall' to remove the installed - files again. - -Compilers and Options -===================== - -Some systems require unusual options for compilation or linking that the -`configure' script does not know about. Run `./configure --help' for -details on some of the pertinent environment variables. - - You can give `configure' initial values for configuration parameters -by setting variables in the command line or in the environment. Here -is an example: - - ./configure CC=c99 CFLAGS=-g LIBS=-lposix - - *Note Defining Variables::, for more details. - -Compiling For Multiple Architectures -==================================== - -You can compile the package for more than one kind of computer at the -same time, by placing the object files for each architecture in their -own directory. To do this, you can use GNU `make'. `cd' to the -directory where you want the object files and executables to go and run -the `configure' script. `configure' automatically checks for the -source code in the directory that `configure' is in and in `..'. - - With a non-GNU `make', it is safer to compile the package for one -architecture at a time in the source code directory. After you have -installed the package for one architecture, use `make distclean' before -reconfiguring for another architecture. - -Installation Names -================== - -By default, `make install' installs the package's commands under -`/usr/local/bin', include files under `/usr/local/include', etc. You -can specify an installation prefix other than `/usr/local' by giving -`configure' the option `--prefix=PREFIX'. - - You can specify separate installation prefixes for -architecture-specific files and architecture-independent files. If you -pass the option `--exec-prefix=PREFIX' to `configure', the package uses -PREFIX as the prefix for installing programs and libraries. -Documentation and other data files still use the regular prefix. - - In addition, if you use an unusual directory layout you can give -options like `--bindir=DIR' to specify different values for particular -kinds of files. Run `configure --help' for a list of the directories -you can set and what kinds of files go in them. - - If the package supports it, you can cause programs to be installed -with an extra prefix or suffix on their names by giving `configure' the -option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. - -Optional Features -================= - -Some packages pay attention to `--enable-FEATURE' options to -`configure', where FEATURE indicates an optional part of the package. -They may also pay attention to `--with-PACKAGE' options, where PACKAGE -is something like `gnu-as' or `x' (for the X Window System). The -`README.md' should mention any `--enable-' and `--with-' options that the -package recognizes. - - For packages that use the X Window System, `configure' can usually -find the X include and library files automatically, but if it doesn't, -you can use the `configure' options `--x-includes=DIR' and -`--x-libraries=DIR' to specify their locations. - -Specifying the System Type -========================== - -There may be some features `configure' cannot figure out automatically, -but needs to determine by the type of machine the package will run on. -Usually, assuming the package is built to be run on the _same_ -architectures, `configure' can figure that out, but if it prints a -message saying it cannot guess the machine type, give it the -`--build=TYPE' option. TYPE can either be a short name for the system -type, such as `sun4', or a canonical name which has the form: - - CPU-COMPANY-SYSTEM - -where SYSTEM can have one of these forms: - - OS KERNEL-OS - - See the file `config.sub' for the possible values of each field. If -`config.sub' isn't included in this package, then this package doesn't -need to know the machine type. - - If you are _building_ compiler tools for cross-compiling, you should -use the option `--target=TYPE' to select the type of system they will -produce code for. - - If you want to _use_ a cross compiler, that generates code for a -platform different from the build platform, you should specify the -"host" platform (i.e., that on which the generated programs will -eventually be run) with `--host=TYPE'. - -Sharing Defaults -================ - -If you want to set default values for `configure' scripts to share, you -can create a site shell script called `config.site' that gives default -values for variables like `CC', `cache_file', and `prefix'. -`configure' looks for `PREFIX/share/config.site' if it exists, then -`PREFIX/etc/config.site' if it exists. Or, you can set the -`CONFIG_SITE' environment variable to the location of the site script. -A warning: not all `configure' scripts look for a site script. - -Defining Variables -================== - -Variables not defined in a site shell script can be set in the -environment passed to `configure'. However, some packages may run -configure again during the build, and the customized values of these -variables may be lost. In order to avoid this problem, you should set -them in the `configure' command line, using `VAR=value'. For example: - - ./configure CC=/usr/local2/bin/gcc - -causes the specified `gcc' to be used as the C compiler (unless it is -overridden in the site shell script). - -Unfortunately, this technique does not work for `CONFIG_SHELL' due to -an Autoconf bug. Until the bug is fixed you can use this workaround: - - CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash - -`configure' Invocation -====================== - -`configure' recognizes the following options to control how it operates. - -`--help' -`-h' - Print a summary of the options to `configure', and exit. - -`--version' -`-V' - Print the version of Autoconf used to generate the `configure' - script, and exit. - -`--cache-file=FILE' - Enable the cache: use and save the results of the tests in FILE, - traditionally `config.cache'. FILE defaults to `/dev/null' to - disable caching. - -`--config-cache' -`-C' - Alias for `--cache-file=config.cache'. - -`--quiet' -`--silent' -`-q' - Do not print messages saying which checks are being made. To - suppress all normal output, redirect it to `/dev/null' (any error - messages will still be shown). - -`--srcdir=DIR' - Look for the package's source code in directory DIR. Usually - `configure' can determine that directory automatically. - -`configure' also accepts some other, not widely useful, options. Run -`configure --help' for more details. - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/Makefile.am b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/Makefile.am deleted file mode 100644 index e750157b091..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/Makefile.am +++ /dev/null @@ -1,260 +0,0 @@ -## Process this file with automake to produce Makefile.in - -AUTOMAKE_OPTIONS = subdir-objects foreign - -# Make sure that when we re-make ./configure, we get the macros we need -ACLOCAL_AMFLAGS = -I m4 - -# This is so we can #include -AM_CPPFLAGS = -I$(top_srcdir)/src - -# This is mostly based on configure options -AM_CXXFLAGS = - -# These are good warnings to turn on by default -if GCC - AM_CXXFLAGS += -Wall -Wwrite-strings -Woverloaded-virtual -Wno-sign-compare -endif - -# These are x86-specific, having to do with frame-pointers -if X86_64 -if ENABLE_FRAME_POINTERS - AM_CXXFLAGS += -fno-omit-frame-pointer -else - # TODO(csilvers): check if -fomit-frame-pointer might be in $(CXXFLAGS), - # before setting this. - AM_CXXFLAGS += -DNO_FRAME_POINTER -endif -endif - -if DISABLE_RTTI - AM_CXXFLAGS += -fno-rtti -endif - -glogincludedir = $(includedir)/glog -## The .h files you want to install (that is, .h files that people -## who install this package can include in their own applications.) -## We have to include both the .h and .h.in forms. The latter we -## put in noinst_HEADERS. -gloginclude_HEADERS = src/glog/log_severity.h -nodist_gloginclude_HEADERS = src/glog/logging.h src/glog/raw_logging.h src/glog/vlog_is_on.h src/glog/stl_logging.h -noinst_HEADERS = src/glog/logging.h.in src/glog/raw_logging.h.in src/glog/vlog_is_on.h.in src/glog/stl_logging.h.in - -docdir = $(prefix)/share/doc/$(PACKAGE)-$(VERSION) -## This is for HTML and other documentation you want to install. -## Add your documentation files (in doc/) in addition to these -## top-level boilerplate files. Also add a TODO file if you have one. -dist_doc_DATA = AUTHORS COPYING ChangeLog INSTALL README.md README.windows \ - doc/designstyle.css doc/glog.html - -## The libraries (.so's) you want to install -lib_LTLIBRARIES = - -# The libraries libglog depends on. -COMMON_LIBS = $(PTHREAD_LIBS) $(GFLAGS_LIBS) $(UNWIND_LIBS) -# Compile switches for our unittest. -TEST_CFLAGS = $(GTEST_CFLAGS) $(GMOCK_CFLAGS) $(GFLAGS_CFLAGS) \ - $(MINGW_CFLAGS) $(AM_CXXFLAGS) -# Libraries for our unittest. -TEST_LIBS = $(GTEST_LIBS) $(GMOCK_LIBS) $(GFLAGS_LIBS) - -## unittests you want to run when people type 'make check'. -## TESTS is for binary unittests, check_SCRIPTS for script-based unittests. -## TESTS_ENVIRONMENT sets environment variables for when you run unittest, -## but it only seems to take effect for *binary* unittests (argh!) -TESTS = -# Set a small stack size so that (at least on Linux) PIEs are mapped at a lower -# address than DSOs. This is used by symbolize_pie_unittest to check that we can -# successfully symbolize PIEs loaded at low addresses. -TESTS_ENVIRONMENT = ulimit -s 8192; -check_SCRIPTS = -# Every time you add a unittest to check_SCRIPTS, add it here too -noinst_SCRIPTS = -# Binaries used for script-based unittests. -TEST_BINARIES = - -TESTS += logging_unittest -logging_unittest_SOURCES = $(gloginclude_HEADERS) \ - src/logging_unittest.cc \ - src/config_for_unittests.h \ - src/mock-log.h -nodist_logging_unittest_SOURCES = $(nodist_gloginclude_HEADERS) -logging_unittest_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -logging_unittest_LDFLAGS = $(PTHREAD_CFLAGS) -logging_unittest_LDADD = libglog.la $(COMMON_LIBS) $(TEST_LIBS) - -check_SCRIPTS += logging_striplog_test_sh -noinst_SCRIPTS += src/logging_striplog_test.sh -logging_striplog_test_sh: logging_striptest0 logging_striptest2 logging_striptest10 - $(top_srcdir)/src/logging_striplog_test.sh - -check_SCRIPTS += demangle_unittest_sh -noinst_SCRIPTS += src/demangle_unittest.sh -demangle_unittest_sh: demangle_unittest - $(builddir)/demangle_unittest # force to create lt-demangle_unittest - $(top_srcdir)/src/demangle_unittest.sh - -check_SCRIPTS += signalhandler_unittest_sh -noinst_SCRIPTS += src/signalhandler_unittest.sh -signalhandler_unittest_sh: signalhandler_unittest - $(builddir)/signalhandler_unittest # force to create lt-signalhandler_unittest - $(top_srcdir)/src/signalhandler_unittest.sh - -TEST_BINARIES += logging_striptest0 -logging_striptest0_SOURCES = $(gloginclude_HEADERS) \ - src/logging_striptest_main.cc -nodist_logging_striptest0_SOURCES = $(nodist_gloginclude_HEADERS) -logging_striptest0_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -logging_striptest0_LDFLAGS = $(PTHREAD_CFLAGS) -logging_striptest0_LDADD = libglog.la $(COMMON_LIBS) - -TEST_BINARIES += logging_striptest2 -logging_striptest2_SOURCES = $(gloginclude_HEADERS) \ - src/logging_striptest2.cc -nodist_logging_striptest2_SOURCES = $(nodist_gloginclude_HEADERS) -logging_striptest2_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -logging_striptest2_LDFLAGS = $(PTHREAD_CFLAGS) -logging_striptest2_LDADD = libglog.la $(COMMON_LIBS) - -TEST_BINARIES += logging_striptest10 -logging_striptest10_SOURCES = $(gloginclude_HEADERS) \ - src/logging_striptest10.cc -nodist_logging_striptest10_SOURCES = $(nodist_gloginclude_HEADERS) -logging_striptest10_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -logging_striptest10_LDFLAGS = $(PTHREAD_CFLAGS) -logging_striptest10_LDADD = libglog.la $(COMMON_LIBS) - -TESTS += demangle_unittest -demangle_unittest_SOURCES = $(gloginclude_HEADERS) \ - src/demangle_unittest.cc -nodist_demangle_unittest_SOURCES = $(nodist_gloginclude_HEADERS) -demangle_unittest_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -demangle_unittest_LDFLAGS = $(PTHREAD_CFLAGS) -demangle_unittest_LDADD = libglog.la $(COMMON_LIBS) $(TEST_LIBS) - -TESTS += stacktrace_unittest -stacktrace_unittest_SOURCES = $(gloginclude_HEADERS) \ - src/stacktrace_unittest.cc -nodist_stacktrace_unittest_SOURCES = $(nodist_gloginclude_HEADERS) -stacktrace_unittest_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -stacktrace_unittest_LDFLAGS = $(PTHREAD_CFLAGS) -stacktrace_unittest_LDADD = libglog.la $(COMMON_LIBS) - -TESTS += symbolize_unittest -symbolize_unittest_SOURCES = $(gloginclude_HEADERS) \ - src/symbolize_unittest.cc -nodist_symbolize_unittest_SOURCES = $(nodist_gloginclude_HEADERS) -symbolize_unittest_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -symbolize_unittest_LDFLAGS = $(PTHREAD_CFLAGS) -symbolize_unittest_LDADD = libglog.la $(COMMON_LIBS) $(TEST_LIBS) - -TESTS += symbolize_pie_unittest -symbolize_pie_unittest_SOURCES = $(gloginclude_HEADERS) \ - src/symbolize_unittest.cc -nodist_symbolize_pie_unittest_SOURCES = $(nodist_gloginclude_HEADERS) -symbolize_pie_unittest_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -fPIE -symbolize_pie_unittest_LDFLAGS = $(PTHREAD_CFLAGS) -pie -symbolize_pie_unittest_LDADD = libglog.la $(COMMON_LIBS) $(TEST_LIBS) - -TESTS += stl_logging_unittest -stl_logging_unittest_SOURCES = $(gloginclude_HEADERS) \ - src/stl_logging_unittest.cc -nodist_stl_logging_unittest_SOURCES = $(nodist_gloginclude_HEADERS) -stl_logging_unittest_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -stl_logging_unittest_LDFLAGS = $(PTHREAD_CFLAGS) -stl_logging_unittest_LDADD = libglog.la $(COMMON_LIBS) $(TEST_LIBS) - -TEST_BINARIES += signalhandler_unittest -signalhandler_unittest_SOURCES = $(gloginclude_HEADERS) \ - src/signalhandler_unittest.cc -nodist_signalhandler_unittest_SOURCES = $(nodist_gloginclude_HEADERS) -signalhandler_unittest_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -signalhandler_unittest_LDFLAGS = $(PTHREAD_CFLAGS) -signalhandler_unittest_LDADD = libglog.la $(COMMON_LIBS) $(TEST_LIBS) - -TESTS += utilities_unittest -utilities_unittest_SOURCES = $(gloginclude_HEADERS) \ - src/utilities_unittest.cc -nodist_utilities_unittest_SOURCES = $(nodist_gloginclude_HEADERS) -utilities_unittest_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -utilities_unittest_LDFLAGS = $(PTHREAD_CFLAGS) -utilities_unittest_LDADD = libglog.la $(COMMON_LIBS) $(TEST_LIBS) - -if HAVE_GMOCK -TESTS += mock_log_test -mock_log_test_SOURCES = $(gloginclude_HEADERS) \ - src/mock-log_test.cc -nodist_mock_log_test_SOURCES = $(nodist_gloginclude_HEADERS) -mock_log_test_CXXFLAGS = $(PTHREAD_CFLAGS) $(TEST_CFLAGS) -mock_log_test_LDFLAGS = $(PTHREAD_CFLAGS) -mock_log_test_LDADD = libglog.la $(COMMON_LIBS) $(TEST_LIBS) -endif - -## vvvv RULES TO MAKE THE LIBRARIES, BINARIES, AND UNITTESTS - -lib_LTLIBRARIES += libglog.la -libglog_la_SOURCES = $(gloginclude_HEADERS) \ - src/logging.cc src/raw_logging.cc src/vlog_is_on.cc \ - src/utilities.cc src/utilities.h \ - src/demangle.cc src/demangle.h \ - src/stacktrace.h \ - src/stacktrace_generic-inl.h \ - src/stacktrace_libunwind-inl.h \ - src/stacktrace_powerpc-inl.h \ - src/stacktrace_x86-inl.h \ - src/stacktrace_x86_64-inl.h \ - src/symbolize.cc src/symbolize.h \ - src/signalhandler.cc \ - src/base/mutex.h src/base/googleinit.h \ - src/base/commandlineflags.h src/googletest.h -nodist_libglog_la_SOURCES = $(nodist_gloginclude_HEADERS) - -libglog_la_CXXFLAGS = $(PTRHEAD_CFLAGS) $(GFLAGS_CFLAGS) $(MINGW_CFLAGS) \ - $(AM_CXXFLAGS) -DNDEBUG -libglog_la_LDFLAGS = $(PTRHEAD_CFLAGS) $(GFLAGS_LDFLAGS) -libglog_la_LIBADD = $(COMMON_LIBS) - -## The location of the windows project file for each binary we make -WINDOWS_PROJECTS = google-glog.sln -WINDOWS_PROJECTS += vsprojects/libglog/libglog.vcproj -WINDOWS_PROJECTS += vsprojects/logging_unittest/logging_unittest.vcproj -WINDOWS_PROJECTS += vsprojects/libglog_static/libglog_static.vcproj -WINDOWS_PROJECTS += vsprojects/logging_unittest_static/logging_unittest_static.vcproj - -## ^^^^ END OF RULES TO MAKE THE LIBRARIES, BINARIES, AND UNITTESTS - - -## This should always include $(TESTS), but may also include other -## binaries that you compile but don't want automatically installed. -noinst_PROGRAMS = $(TESTS) $(TEST_BINARIES) - -rpm: dist-gzip packages/rpm.sh packages/rpm/rpm.spec - @cd packages && ./rpm.sh ${PACKAGE} ${VERSION} - -deb: dist-gzip packages/deb.sh packages/deb/* - @cd packages && ./deb.sh ${PACKAGE} ${VERSION} - -# Windows wants write permission to .vcproj files and maybe even sln files. -dist-hook: - test -e "$(distdir)/vsprojects" \ - && chmod -R u+w $(distdir)/*.sln $(distdir)/vsprojects/ - -libtool: $(LIBTOOL_DEPS) - $(SHELL) ./config.status --recheck - -EXTRA_DIST = packages/rpm.sh packages/rpm/rpm.spec \ - packages/deb.sh packages/deb/* \ - $(SCRIPTS) src/logging_unittest.err src/demangle_unittest.txt \ - src/windows/config.h src/windows/port.h src/windows/port.cc \ - src/windows/preprocess.sh \ - src/windows/glog/log_severity.h src/windows/glog/logging.h \ - src/windows/glog/raw_logging.h src/windows/glog/stl_logging.h \ - src/windows/glog/vlog_is_on.h \ - $(WINDOWS_PROJECTS) - -CLEANFILES = core demangle.dm demangle.nm signalhandler.out* \ - signalhandler_unittest.*.log.INFO.* - -# Add pkgconfig file -pkgconfigdir = $(libdir)/pkgconfig -pkgconfig_DATA = libglog.pc diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/README.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/README.md deleted file mode 100644 index 965766c7caf..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/README.md +++ /dev/null @@ -1,10 +0,0 @@ -[![Build Status](https://img.shields.io/travis/google/glog/master.svg?label=Travis)](https://travis-ci.org/google/glog/builds) -[![Grunt status](https://img.shields.io/appveyor/ci/google-admin/glog/master.svg?label=Appveyor)](https://ci.appveyor.com/project/google-admin/glog/history) - -This repository contains a C++ implementation of the Google logging -module. Documentation for the implementation is in doc/. - -See INSTALL for (generic) installation instructions for C++: basically -```sh -./autogen.sh && ./configure && make && make install -``` diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/README.windows b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/README.windows deleted file mode 100644 index ea6ccc20bde..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/README.windows +++ /dev/null @@ -1,17 +0,0 @@ -This project has been ported to Windows, including stack tracing, signal -handling, and unit tests. - -A Visual Studio solution file is explicitly not provided because it is not -maintainable. Instead, a CMake build system exists to generate the correct -solution for your version of Visual Studio. - -In short, - (1) Install CMake from: https://cmake.org/download/ - (2) With CMake on your PATH, run `cmake .` to generate the build files - (3) Either use `cmake --build`, or open the generated solution - -CMake provides different generators, and by default will pick the most relevant -one to your environment. If you need a specific version of Visual Studio, use -`cmake . -G `, and see `cmake --help` for the available -generators. Also see `-T `, which can used to request the native -x64 toolchain with `-T host=x64`. \ No newline at end of file diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/WORKSPACE b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/WORKSPACE deleted file mode 100644 index b5760d04caa..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/WORKSPACE +++ /dev/null @@ -1,10 +0,0 @@ -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -http_archive( - name = "com_github_gflags_gflags", - strip_prefix = "gflags-2.2.2", - urls = [ - "https://mirror.bazel.build/github.com/gflags/gflags/archive/v2.2.2.tar.gz", - "https://github.com/gflags/gflags/archive/v2.2.2.tar.gz", - ], -) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/appveyor.yml b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/appveyor.yml deleted file mode 100644 index ecc42c4f291..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/appveyor.yml +++ /dev/null @@ -1,71 +0,0 @@ -# global environment variables -environment: - global: - # path to source directory of project to be built - PROJECT_DIR: . - # output test results for failing tests - CTEST_OUTPUT_ON_FAILURE: 1 - - # test matrix - matrix: - - - TOOLCHAIN: "vs-14-2015-sdk-8-1" - GENERATOR: "Visual Studio 14 2015 Win64" - TEST_TARGET: RUN_TESTS - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - - - TOOLCHAIN: "vs-14-2015-win64" - GENERATOR: "Visual Studio 14 2015 Win64" - TEST_TARGET: RUN_TESTS - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - - - TOOLCHAIN: "vs-15-2017-win64" - GENERATOR: "Visual Studio 15 2017 Win64" - TEST_TARGET: RUN_TESTS - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - - - TOOLCHAIN: "vs-15-2017-win64-cxx17" - GENERATOR: "Visual Studio 15 2017 Win64" - TEST_TARGET: RUN_TESTS - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - - - TOOLCHAIN: "mingw-cxx11" - GENERATOR: "MinGW Makefiles" - MINGW_PATH: "C:\\mingw-w64\\x86_64-7.2.0-posix-seh-rt_v5-rev1\\mingw64\\bin" - TEST_TARGET: test - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - - - TOOLCHAIN: "mingw-gnuxx11" - GENERATOR: "MinGW Makefiles" - MINGW_PATH: "C:\\mingw-w64\\x86_64-7.2.0-posix-seh-rt_v5-rev1\\mingw64\\bin" - TEST_TARGET: test - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - - - TOOLCHAIN: "mingw-cxx17" - GENERATOR: "MinGW Makefiles" - MINGW_PATH: "C:\\mingw-w64\\x86_64-7.2.0-posix-seh-rt_v5-rev1\\mingw64\\bin" - TEST_TARGET: test - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - -install: - # Remove entry with sh.exe from PATH to fix error with MinGW toolchain - # (For MinGW make to work correctly sh.exe must NOT be in your path) - # * http://stackoverflow.com/a/3870338/2288008 - - cmd: set PATH=%PATH:C:\Program Files\Git\usr\bin;=% - - # set MINGW path - - cmd: IF DEFINED MINGW_PATH set PATH=%MINGW_PATH%;%PATH% - - # Visual Studio 15 2017: Mimic behavior of older versions - - cmd: set VS150COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\Tools - -build_script: - - cmd: cmake -H. -B_build_%TOOLCHAIN%_Debug -G "%GENERATOR%" -DCMAKE_TOOLCHAIN_FILE="%cd%\toolchains\%TOOLCHAIN%.cmake" - - cmd: cmake --build _build_%TOOLCHAIN%_Debug --config Debug - #- cmd: cmake -H. -B_build_%TOOLCHAIN%_Release -G "%GENERATOR%" -DCMAKE_TOOLCHAIN_FILE="%cd%\toolchains\%TOOLCHAIN%.cmake" - #- cmd: cmake --build _build_%TOOLCHAIN%_Release --config Release - # add git back to PATH for `diff` command in case of error - - cmd: set PATH=C:\Program Files\Git\usr\bin;%PATH% - - cmd: IF DEFINED TEST_TARGET cmake --build _build_%TOOLCHAIN%_Debug --target %TEST_TARGET% - #- cmd: IF DEFINED TEST_TARGET cmake --build _build_%TOOLCHAIN%_Release --target %TEST_TARGET% - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/autogen.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/autogen.sh deleted file mode 100755 index 08b65904095..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/autogen.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -set -eu - -autoreconf -i diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/bazel/example/BUILD b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/bazel/example/BUILD deleted file mode 100644 index 6b10e2b2fb3..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/bazel/example/BUILD +++ /dev/null @@ -1,8 +0,0 @@ -cc_test( - name = "main", - size = "small", - srcs = ["main.cc"], - deps = [ - "//:glog", - ], -) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/bazel/example/main.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/bazel/example/main.cc deleted file mode 100644 index fef01dc1575..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/bazel/example/main.cc +++ /dev/null @@ -1,22 +0,0 @@ -#include -#include -#include - -int main(int argc, char* argv[]) { - // Initialize Google's logging library. - google::InitGoogleLogging(argv[0]); - - // Optional: parse command line flags - gflags::ParseCommandLineFlags(&argc, &argv, true); - - LOG(INFO) << "Hello, world!"; - - // glog/stl_logging.h allows logging STL containers. - std::vector x; - x.push_back(1); - x.push_back(2); - x.push_back(3); - LOG(INFO) << "ABC, it's easy as " << x; - - return 0; -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/bazel/glog.bzl b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/bazel/glog.bzl deleted file mode 100644 index 4a1bc6c5388..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/bazel/glog.bzl +++ /dev/null @@ -1,148 +0,0 @@ -# Implement a macro glog_library() that the BUILD file can load. - -# By default, glog is built with gflags support. You can change this behavior -# by using glog_library(with_gflags=0) -# -# This file is inspired by the following sample BUILD files: -# https://github.com/google/glog/issues/61 -# https://github.com/google/glog/files/393474/BUILD.txt - -def glog_library(namespace='google', with_gflags=1, **kwargs): - if native.repository_name() != '@': - gendir = '$(GENDIR)/external/' + native.repository_name().lstrip('@') - else: - gendir = '$(GENDIR)' - - native.cc_library( - name = 'glog', - visibility = [ '//visibility:public' ], - srcs = [ - ':config_h', - 'src/base/commandlineflags.h', - 'src/base/googleinit.h', - 'src/base/mutex.h', - 'src/demangle.cc', - 'src/demangle.h', - 'src/logging.cc', - 'src/raw_logging.cc', - 'src/signalhandler.cc', - 'src/stacktrace.h', - 'src/stacktrace_generic-inl.h', - 'src/stacktrace_libunwind-inl.h', - 'src/stacktrace_powerpc-inl.h', - 'src/stacktrace_windows-inl.h', - 'src/stacktrace_x86-inl.h', - 'src/stacktrace_x86_64-inl.h', - 'src/symbolize.cc', - 'src/symbolize.h', - 'src/utilities.cc', - 'src/utilities.h', - 'src/vlog_is_on.cc', - ], - hdrs = [ - ':logging_h', - ':raw_logging_h', - ':stl_logging_h', - ':vlog_is_on_h', - 'src/glog/log_severity.h', - ], - strip_include_prefix = 'src', - copts = [ - # Disable warnings that exists in glog. - '-Wno-sign-compare', - '-Wno-unused-function', - '-Wno-unused-local-typedefs', - '-Wno-unused-variable', - "-DGLOG_BAZEL_BUILD", - # Inject a C++ namespace. - "-DGOOGLE_NAMESPACE='%s'" % namespace, - # Allows src/base/mutex.h to include pthread.h. - '-DHAVE_PTHREAD', - # Allows src/logging.cc to determine the host name. - '-DHAVE_SYS_UTSNAME_H', - # For src/utilities.cc. - '-DHAVE_SYS_SYSCALL_H', - '-DHAVE_SYS_TIME_H', - '-DHAVE_STDINT_H', - '-DHAVE_STRING_H', - # Enable dumping stacktrace upon sigaction. - '-DHAVE_SIGACTION', - # For logging.cc. - '-DHAVE_PREAD', - '-DHAVE___ATTRIBUTE__', - - # Include generated header files. - '-I%s/glog_internal' % gendir, - ] + select({ - # For stacktrace. - '@bazel_tools//src/conditions:darwin': [ - '-DHAVE_UNWIND_H', - '-DHAVE_DLADDR', - ], - '//conditions:default': [ - '-DHAVE_UNWIND_H', - ], - }) + ([ - # Use gflags to parse CLI arguments. - '-DHAVE_LIB_GFLAGS', - ] if with_gflags else []), - deps = [ - '@com_github_gflags_gflags//:gflags', - ] if with_gflags else [], - **kwargs - ) - - native.genrule( - name = 'gen_sh', - outs = [ - 'gen.sh', - ], - cmd = r'''\ -#!/bin/sh -cat > $@ <<"EOF" -sed -e 's/@ac_cv_cxx_using_operator@/1/g' \ - -e 's/@ac_cv_have_unistd_h@/1/g' \ - -e 's/@ac_cv_have_stdint_h@/1/g' \ - -e 's/@ac_cv_have_systypes_h@/1/g' \ - -e 's/@ac_cv_have_libgflags@/{}/g' \ - -e 's/@ac_cv_have_uint16_t@/1/g' \ - -e 's/@ac_cv_have___builtin_expect@/1/g' \ - -e 's/@ac_cv_have_.*@/0/g' \ - -e 's/@ac_google_start_namespace@/namespace google {{/g' \ - -e 's/@ac_google_end_namespace@/}}/g' \ - -e 's/@ac_google_namespace@/google/g' \ - -e 's/@ac_cv___attribute___noinline@/__attribute__((noinline))/g' \ - -e 's/@ac_cv___attribute___noreturn@/__attribute__((noreturn))/g' \ - -e 's/@ac_cv___attribute___printf_4_5@/__attribute__((__format__ (__printf__, 4, 5)))/g' -EOF -'''.format(int(with_gflags)), - ) - - native.genrule( - name = 'config_h', - srcs = [ - 'src/config.h.cmake.in', - ], - outs = [ - 'glog_internal/config.h', - ], - cmd = "awk '{ gsub(/^#cmakedefine/, \"//cmakedefine\"); print; }' $< > $@", - ) - - [native.genrule( - name = '%s_h' % f, - srcs = [ - 'src/glog/%s.h.in' % f, - ], - outs = [ - 'src/glog/%s.h' % f, - ], - cmd = '$(location :gen_sh) < $< > $@', - tools = [':gen_sh'], - ) for f in [ - 'vlog_is_on', - 'stl_logging', - 'raw_logging', - 'logging', - ] - ] diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/cmake/INSTALL.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/cmake/INSTALL.md deleted file mode 100644 index 1377d652ed0..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/cmake/INSTALL.md +++ /dev/null @@ -1,81 +0,0 @@ -# Glog - CMake Support - -Glog comes with a CMake build script ([CMakeLists.txt](../CMakeLists.txt)) that can be used on a wide range of platforms. -If you don't have CMake installed already, you can download it for free from . - -CMake works by generating native makefiles or build projects that can be used in the compiler environment of your choice. -You can either build Glog with CMake as a standalone project or it can be incorporated into an existing CMake build for another project. - -## Table of Contents - -- [Building Glog with CMake](#building-glog-with-cmake) -- [Consuming Glog in a CMake Project](#consuming-glog-in-a-cmake-project) -- [Incorporating Glog into a CMake Project](#incorporating-glog-into-a-cmake-project) - -## Building Glog with CMake - -When building Glog as a standalone project, on Unix-like systems with GNU Make as build tool, the typical workflow is: - -1. Get the source code and change to it. -e.g. cloning with git: -```bash -git clone git@github.com:google/glog.git -cd glog -``` - -2. Run CMake to configure the build tree. -```bash -cmake -H. -Bbuild -G "Unix Makefiles" -``` -note: To get the list of available generators (e.g. Visual Studio), use `-G ""` - -3. Afterwards, generated files can be used to compile the project. -```bash -cmake --build build -``` - -4. Test the build software (optional). -```bash -cmake --build build --target test -``` - -5. Install the built files (optional). -```bash -cmake --build build --target install -``` - -## Consuming Glog in a CMake Project - -If you have Glog installed in your system, you can use the CMake command -`find_package()` to include it in your CMake Project. - -```cmake -cmake_minimum_required(VERSION 3.0.2) -project(myproj VERSION 1.0) - -find_package(glog 0.4.0 REQUIRED) - -add_executable(myapp main.cpp) -target_link_libraries(myapp glog::glog) -``` - -Compile definitions and options will be added automatically to your target as -needed. - -## Incorporating Glog into a CMake Project - -You can also use the CMake command `add_subdirectory()` to include Glog directly from a subdirectory of your project. -The **glog::glog** target is in this case an ALIAS library target for the **glog** library target. - -```cmake -cmake_minimum_required(VERSION 3.0.2) -project(myproj VERSION 1.0) - -add_subdirectory(glog) - -add_executable(myapp main.cpp) -target_link_libraries(myapp glog::glog) -``` - -Again, compile definitions and options will be added automatically to your target as -needed. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/configure.ac b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/configure.ac deleted file mode 100644 index 02c118c0278..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/configure.ac +++ /dev/null @@ -1,246 +0,0 @@ -## Process this file with autoconf to produce configure. -## In general, the safest way to proceed is to run the following: -## % aclocal -I . -I `pwd`/../autoconf && autoheader && autoconf && automake - -# make sure we're interpreted by some minimal autoconf -AC_PREREQ(2.57) - -AC_INIT(glog, 0.4.0, opensource@google.com) -# The argument here is just something that should be in the current directory -# (for sanity checking) -AC_CONFIG_SRCDIR(README.md) -AC_CONFIG_MACRO_DIR([m4]) -AM_INIT_AUTOMAKE -AM_CONFIG_HEADER(src/config.h) - -AC_LANG(C++) - -# Checks for programs. -AC_PROG_CC -AC_PROG_CPP -AC_PROG_CXX -AM_CONDITIONAL(GCC, test "$GCC" = yes) # let the Makefile know if we're gcc - -AC_PROG_LIBTOOL -AC_SUBST(LIBTOOL_DEPS) - -# Check whether some low-level functions/files are available -AC_HEADER_STDC - -# These are tested for by AC_HEADER_STDC, but I check again to set the var -AC_CHECK_HEADER(stdint.h, ac_cv_have_stdint_h=1, ac_cv_have_stdint_h=0) -AC_CHECK_HEADER(sys/types.h, ac_cv_have_systypes_h=1, ac_cv_have_systypes_h=0) -AC_CHECK_HEADER(inttypes.h, ac_cv_have_inttypes_h=1, ac_cv_have_inttypes_h=0) -AC_CHECK_HEADER(pwd.h, ac_cv_have_pwd_h=1, ac_cv_have_pwd_h=0) -AC_CHECK_HEADERS(unistd.h, ac_cv_have_unistd_h=1, ac_cv_have_unistd_h=0) -AC_CHECK_HEADERS(syscall.h) -AC_CHECK_HEADERS(sys/syscall.h) -# For backtrace with glibc. -AC_CHECK_HEADERS(execinfo.h) -# For backtrace with libunwind. -AC_CHECK_HEADERS(libunwind.h, ac_cv_have_libunwind_h=1, ac_cv_have_libunwind_h=0) -AC_CHECK_HEADERS(ucontext.h) -AC_CHECK_HEADERS(sys/utsname.h) -AC_CHECK_HEADERS(pwd.h) -AC_CHECK_HEADERS(syslog.h) -AC_CHECK_HEADERS(sys/time.h) -AC_CHECK_HEADERS(glob.h) -# For backtrace with gcc. -AC_CHECK_HEADERS(unwind.h) - -AC_CHECK_HEADER(windows.h, ac_cv_have_windows_h=1, ac_cv_have_windows_h=0) -if test x"$ac_cv_have_windows_h" = x"1"; then - MINGW_CFLAGS=-Isrc/windows -fi - -AC_CHECK_SIZEOF(void *) - -# These are the types I need. We look for them in either stdint.h, -# sys/types.h, or inttypes.h, all of which are part of the default-includes. -AC_CHECK_TYPE(uint16_t, ac_cv_have_uint16_t=1, ac_cv_have_uint16_t=0) -AC_CHECK_TYPE(u_int16_t, ac_cv_have_u_int16_t=1, ac_cv_have_u_int16_t=0) -AC_CHECK_TYPE(__uint16, ac_cv_have___uint16=1, ac_cv_have___uint16=0) - -AC_CHECK_FUNC(sigaltstack, - AC_DEFINE(HAVE_SIGALTSTACK, 1, - [Define if you have the `sigaltstack' function])) -AC_CHECK_FUNC(sigaction, - AC_DEFINE(HAVE_SIGACTION, 1, - [Define if you have the 'sigaction' function])) -AC_CHECK_FUNC(dladdr, - AC_DEFINE(HAVE_DLADDR, 1, - [Define if you have the `dladdr' function])) -AC_CHECK_FUNC(fcntl, - AC_DEFINE(HAVE_FCNTL, 1, - [Define if you have the `fcntl' function])) -AC_CHECK_FUNC(pread, - AC_DEFINE(HAVE_PREAD, 1, - [Define if you have the 'pread' function])) -AC_CHECK_FUNC(pwrite, - AC_DEFINE(HAVE_PWRITE, 1, - [Define if you have the 'pwrite' function])) - -AX_C___ATTRIBUTE__ -# We only care about these two attributes. -if test x"$ac_cv___attribute__" = x"yes"; then - ac_cv___attribute___noreturn="__attribute__ ((noreturn))" - ac_cv___attribute___noinline="__attribute__ ((noinline))" - ac_cv___attribute___printf_4_5="__attribute__((__format__ (__printf__, 4, 5)))" -else - ac_cv___attribute___noreturn= - ac_cv___attribute___noinline= - ac_cv___attribute___printf_4_5= -fi - -AX_C___BUILTIN_EXPECT -if test x"$ac_cv___builtin_expect" = x"yes"; then - ac_cv_have___builtin_expect=1 -else - ac_cv_have___builtin_expect=0 -fi - -AX_C___SYNC_VAL_COMPARE_AND_SWAP - -# On x86_64, instead of libunwind, we can choose to compile with frame-pointers -# (This isn't needed on i386, where -fno-omit-frame-pointer is the default). -AC_ARG_ENABLE(frame_pointers, - AS_HELP_STRING([--enable-frame-pointers], - [On x86_64 systems, compile with -fno-omit-frame-pointer (see INSTALL)]),, - enable_frame_pointers=no) -AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __x86_64__ == 1 ? 0 : 1])], - [is_x86_64=yes], [is_x86_64=no]) -AM_CONDITIONAL(ENABLE_FRAME_POINTERS, test "$enable_frame_pointers" = yes) -AM_CONDITIONAL(X86_64, test "$is_x86_64" = yes) - -AC_ARG_ENABLE(rtti, - AS_HELP_STRING([--disable-rtti], - [Disable RTTI in glog])) -AM_CONDITIONAL(DISABLE_RTTI, test x"$enable_rtti" = x"no") -if test x"$enable_rtti" = x"no"; then - AC_DEFINE(DISABLE_RTTI, 1, [define if glog doesn't use RTTI]) -fi - -# Some of the code in this directory depends on pthreads -ACX_PTHREAD -if test x"$acx_pthread_ok" = x"yes"; then - # To make libglog depend on libpthread on Linux, we need to add - # -lpthread in addition to -pthread. - AC_CHECK_LIB(pthread, pthread_self) -fi - -# Check if there is google-gflags library installed. -SAVE_CFLAGS="$CFLAGS" -SAVE_LIBS="$LIBS" -AC_ARG_WITH(gflags, AS_HELP_STRING[--with-gflags=GFLAGS_DIR], - GFLAGS_CFLAGS="-I${with_gflags}/include" - GFLAGS_LIBS="-L${with_gflags}/lib -lgflags" - CFLAGS="$CFLAGS $GFLAGS_CFLAGS" - LIBS="$LIBS $GFLAGS_LIBS" -) -AC_CHECK_LIB(gflags, main, ac_cv_have_libgflags=1, ac_cv_have_libgflags=0) -if test x"$ac_cv_have_libgflags" = x"1"; then - AC_DEFINE(HAVE_LIB_GFLAGS, 1, [define if you have google gflags library]) - if test x"$GFLAGS_LIBS" = x""; then - GFLAGS_LIBS="-lgflags" - fi -else - GFLAGS_CFLAGS= - GFLAGS_LIBS= -fi -CFLAGS="$SAVE_CFLAGS" -LIBS="$SAVE_LIBS" - -# TODO(hamaji): Use official m4 macros provided by testing libraries -# once the m4 macro of Google Mocking becomes ready. -# Check if there is Google Test library installed. -AC_CHECK_PROG(GTEST_CONFIG, gtest-config, "yes") -AC_CHECK_LIB(gtest, main, have_gtest_lib="yes") -if test x"$GTEST_CONFIG" = "xyes" -a x"$have_gtest_lib" = "xyes"; then - GTEST_CFLAGS=`gtest-config --cppflags --cxxflags` - GTEST_LIBS=`gtest-config --ldflags --libs` - AC_DEFINE(HAVE_LIB_GTEST, 1, [define if you have google gtest library]) - - # Check if there is Google Mocking library installed. - AC_CHECK_PROG(GMOCK_CONFIG, gmock-config, "yes") - if test x"$GMOCK_CONFIG" = "xyes"; then - GMOCK_CFLAGS=`gmock-config --cppflags --cxxflags` - GMOCK_LIBS=`gmock-config --ldflags --libs` - AC_DEFINE(HAVE_LIB_GMOCK, 1, [define if you have google gmock library]) - else - # We don't run test cases which use Google Mocking framework. - GMOCK_CFLAGS= - GMOCK_LIBS= - fi -else - # We'll use src/googletest.h for our unittests. - GTEST_CFLAGS= - GTEST_LIBS= -fi -AM_CONDITIONAL(HAVE_GMOCK, test x"$GMOCK_CONFIG" = "xyes") - -# We want to link in libunwind if it exists -UNWIND_LIBS= -# Unfortunately, we need to check the header file in addition to the -# lib file to check if libunwind is available since libunwind-0.98 -# doesn't install all necessary header files. -if test x"$ac_cv_have_libunwind_h" = x"1"; then - AC_CHECK_LIB(unwind, backtrace, UNWIND_LIBS=-lunwind) -fi -AC_SUBST(UNWIND_LIBS) -if test x"$UNWIND_LIBS" != x""; then - AC_DEFINE(HAVE_LIB_UNWIND, 1, [define if you have libunwind]) -fi - -# We'd like to use read/write locks in several places in the code. -# See if our pthreads support extends to that. Note: for linux, it -# does as long as you define _XOPEN_SOURCE appropriately. -AC_RWLOCK - -# Find out what namespace 'normal' STL code lives in, and also what namespace -# the user wants our classes to be defined in -AC_CXX_STL_NAMESPACE -AC_DEFINE_GOOGLE_NAMESPACE(google) - -AC_CXX_USING_OPERATOR - -AC_PC_FROM_UCONTEXT(AC_MSG_WARN(Could not find the PC. Will not output failed addresses...)) - -AC_DEFINE_UNQUOTED(TEST_SRC_DIR, "$srcdir", [location of source code]) - -AC_ARG_ENABLE(unsymbolized-traces, - AS_HELP_STRING([--enable-unsymbolized-traces], - [Print raw pc values when symbolization is failed.]), - enable_unsymbolized_traces=yes) -if test x"$enable_unsymbolized_traces" = x"yes"; then - AC_DEFINE(PRINT_UNSYMBOLIZED_STACK_TRACES, 1, - [define if we should print raw pc values on symbolization failure.]) -fi - -# These are what's needed by logging.h.in and raw_logging.h.in -AC_SUBST(ac_google_start_namespace) -AC_SUBST(ac_google_end_namespace) -AC_SUBST(ac_google_namespace) -AC_SUBST(ac_cv_cxx_using_operator) -AC_SUBST(ac_cv___attribute___noreturn) -AC_SUBST(ac_cv___attribute___noinline) -AC_SUBST(ac_cv___attribute___printf_4_5) -AC_SUBST(ac_cv_have___builtin_expect) -AC_SUBST(ac_cv_have_stdint_h) -AC_SUBST(ac_cv_have_systypes_h) -AC_SUBST(ac_cv_have_inttypes_h) -AC_SUBST(ac_cv_have_unistd_h) -AC_SUBST(ac_cv_have_uint16_t) -AC_SUBST(ac_cv_have_u_int16_t) -AC_SUBST(ac_cv_have___uint16) -AC_SUBST(ac_cv_have_libgflags) -AC_SUBST(GFLAGS_CFLAGS) -AC_SUBST(GTEST_CFLAGS) -AC_SUBST(GMOCK_CFLAGS) -AC_SUBST(MINGW_CFLAGS) -AC_SUBST(GFLAGS_LIBS) -AC_SUBST(GTEST_LIBS) -AC_SUBST(GMOCK_LIBS) - -# Write generated configuration file -AC_CONFIG_FILES([Makefile src/glog/logging.h src/glog/raw_logging.h src/glog/vlog_is_on.h src/glog/stl_logging.h]) -AC_OUTPUT(libglog.pc) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/doc/designstyle.css b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/doc/designstyle.css deleted file mode 100644 index f5d1ec2f767..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/doc/designstyle.css +++ /dev/null @@ -1,115 +0,0 @@ -body { - background-color: #ffffff; - color: black; - margin-right: 1in; - margin-left: 1in; -} - - -h1, h2, h3, h4, h5, h6 { - color: #3366ff; - font-family: sans-serif; -} -@media print { - /* Darker version for printing */ - h1, h2, h3, h4, h5, h6 { - color: #000080; - font-family: helvetica, sans-serif; - } -} - -h1 { - text-align: center; - font-size: 18pt; -} -h2 { - margin-left: -0.5in; -} -h3 { - margin-left: -0.25in; -} -h4 { - margin-left: -0.125in; -} -hr { - margin-left: -1in; -} - -/* Definition lists: definition term bold */ -dt { - font-weight: bold; -} - -address { - text-align: right; -} -/* Use the tag for bits of code and for variables and objects. */ -code,pre,samp,var { - color: #006000; -} -/* Use the tag for file and directory paths and names. */ -file { - color: #905050; - font-family: monospace; -} -/* Use the tag for stuff the user should type. */ -kbd { - color: #600000; -} -div.note p { - float: right; - width: 3in; - margin-right: 0%; - padding: 1px; - border: 2px solid #6060a0; - background-color: #fffff0; -} - -UL.nobullets { - list-style-type: none; - list-style-image: none; - margin-left: -1em; -} - -/* -body:after { - content: "Google Confidential"; -} -*/ - -/* pretty printing styles. See prettify.js */ -.str { color: #080; } -.kwd { color: #008; } -.com { color: #800; } -.typ { color: #606; } -.lit { color: #066; } -.pun { color: #660; } -.pln { color: #000; } -.tag { color: #008; } -.atn { color: #606; } -.atv { color: #080; } -pre.prettyprint { padding: 2px; border: 1px solid #888; } - -.embsrc { background: #eee; } - -@media print { - .str { color: #060; } - .kwd { color: #006; font-weight: bold; } - .com { color: #600; font-style: italic; } - .typ { color: #404; font-weight: bold; } - .lit { color: #044; } - .pun { color: #440; } - .pln { color: #000; } - .tag { color: #006; font-weight: bold; } - .atn { color: #404; } - .atv { color: #060; } -} - -/* Table Column Headers */ -.hdr { - color: #006; - font-weight: bold; - background-color: #dddddd; } -.hdr2 { - color: #006; - background-color: #eeeeee; } \ No newline at end of file diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/doc/glog.html b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/doc/glog.html deleted file mode 100644 index 0edaa66e769..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/doc/glog.html +++ /dev/null @@ -1,613 +0,0 @@ - - - - -How To Use Google Logging Library (glog) - - - - - - - - - -

How To Use Google Logging Library (glog)

-(as of -) - -
- -
- -

Google glog is a library that implements application-level -logging. This library provides logging APIs based on C++-style -streams and various helper macros. -You can log a message by simply streaming things to LOG(<a -particular severity level>), e.g. - -

-   #include <glog/logging.h>
-
-   int main(int argc, char* argv[]) {
-     // Initialize Google's logging library.
-     google::InitGoogleLogging(argv[0]);
-
-     // ...
-     LOG(INFO) << "Found " << num_cookies << " cookies";
-   }
-
- -

Google glog defines a series of macros that simplify many common logging -tasks. You can log messages by severity level, control logging -behavior from the command line, log based on conditionals, abort the -program when expected conditions are not met, introduce your own -verbose logging levels, and more. This document describes the -functionality supported by glog. Please note that this document -doesn't describe all features in this library, but the most useful -ones. If you want to find less common features, please check -header files under src/glog directory. - -

Severity Level

- -

-You can specify one of the following severity levels (in -increasing order of severity): INFO, WARNING, -ERROR, and FATAL. -Logging a FATAL message terminates the program (after the -message is logged). -Note that messages of a given severity are logged not only in the -logfile for that severity, but also in all logfiles of lower severity. -E.g., a message of severity FATAL will be logged to the -logfiles of severity FATAL, ERROR, -WARNING, and INFO. - -

-The DFATAL severity logs a FATAL error in -debug mode (i.e., there is no NDEBUG macro defined), but -avoids halting the program in production by automatically reducing the -severity to ERROR. - -

Unless otherwise specified, glog writes to the filename -"/tmp/<program name>.<hostname>.<user name>.log.<severity level>.<date>.<time>.<pid>" -(e.g., "/tmp/hello_world.example.com.hamaji.log.INFO.20080709-222411.10474"). -By default, glog copies the log messages of severity level -ERROR or FATAL to standard error (stderr) -in addition to log files. - -

Setting Flags

- -

Several flags influence glog's output behavior. -If the Google -gflags library is installed on your machine, the -configure script (see the INSTALL file in the package for -detail of this script) will automatically detect and use it, -allowing you to pass flags on the command line. For example, if you -want to turn the flag --logtostderr on, you can start -your application with the following command line: - -

-   ./your_application --logtostderr=1
-
- -If the Google gflags library isn't installed, you set flags via -environment variables, prefixing the flag name with "GLOG_", e.g. - -
-   GLOG_logtostderr=1 ./your_application
-
- - - -

The following flags are most commonly used: - -

-
logtostderr (bool, default=false) -
Log messages to stderr instead of logfiles.
-Note: you can set binary flags to true by specifying -1, true, or yes (case -insensitive). -Also, you can set binary flags to false by specifying -0, false, or no (again, case -insensitive). -
stderrthreshold (int, default=2, which -is ERROR) -
Copy log messages at or above this level to stderr in -addition to logfiles. The numbers of severity levels -INFO, WARNING, ERROR, and -FATAL are 0, 1, 2, and 3, respectively. -
minloglevel (int, default=0, which -is INFO) -
Log messages at or above this level. Again, the numbers of -severity levels INFO, WARNING, -ERROR, and FATAL are 0, 1, 2, and 3, -respectively. -
log_dir (string, default="") -
If specified, logfiles are written into this directory instead -of the default logging directory. -
v (int, default=0) -
Show all VLOG(m) messages for m less or -equal the value of this flag. Overridable by --vmodule. -See the section about verbose logging for more -detail. -
vmodule (string, default="") -
Per-module verbose level. The argument has to contain a -comma-separated list of <module name>=<log level>. -<module name> -is a glob pattern (e.g., gfs* for all modules whose name -starts with "gfs"), matched against the filename base -(that is, name ignoring .cc/.h./-inl.h). -<log level> overrides any value given by --v. -See also the section about verbose logging. -
- -

There are some other flags defined in logging.cc. Please grep the -source code for "DEFINE_" to see a complete list of all flags. - -

You can also modify flag values in your program by modifying global -variables FLAGS_* . Most settings start working -immediately after you update FLAGS_* . The exceptions are -the flags related to destination files. For example, you might want to -set FLAGS_log_dir before -calling google::InitGoogleLogging . Here is an example: - -

-   LOG(INFO) << "file";
-   // Most flags work immediately after updating values.
-   FLAGS_logtostderr = 1;
-   LOG(INFO) << "stderr";
-   FLAGS_logtostderr = 0;
-   // This won't change the log destination. If you want to set this
-   // value, you should do this before google::InitGoogleLogging .
-   FLAGS_log_dir = "/some/log/directory";
-   LOG(INFO) << "the same file";
-
- -

Conditional / Occasional Logging

- -

Sometimes, you may only want to log a message under certain -conditions. You can use the following macros to perform conditional -logging: - -

-   LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
-
- -The "Got lots of cookies" message is logged only when the variable -num_cookies exceeds 10. - -If a line of code is executed many times, it may be useful to only log -a message at certain intervals. This kind of logging is most useful -for informational messages. - -
-   LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
-
- -

The above line outputs a log messages on the 1st, 11th, -21st, ... times it is executed. Note that the special -google::COUNTER value is used to identify which repetition is -happening. - -

You can combine conditional and occasional logging with the -following macro. - -

-   LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
-                                           << "th big cookie";
-
- -

Instead of outputting a message every nth time, you can also limit -the output to the first n occurrences: - -

-   LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";
-
- -

Outputs log messages for the first 20 times it is executed. Again, -the google::COUNTER identifier indicates which repetition is -happening. - -

Debug Mode Support

- -

Special "debug mode" logging macros only have an effect in debug -mode and are compiled away to nothing for non-debug mode -compiles. Use these macros to avoid slowing down your production -application due to excessive logging. - -

-   DLOG(INFO) << "Found cookies";
-
-   DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
-
-   DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
-
- -

CHECK Macros

- -

It is a good practice to check expected conditions in your program -frequently to detect errors as early as possible. The -CHECK macro provides the ability to abort the application -when a condition is not met, similar to the assert macro -defined in the standard C library. - -

CHECK aborts the application if a condition is not -true. Unlike assert, it is *not* controlled by -NDEBUG, so the check will be executed regardless of -compilation mode. Therefore, fp->Write(x) in the -following example is always executed: - -

-   CHECK(fp->Write(x) == 4) << "Write failed!";
-
- -

There are various helper macros for -equality/inequality checks - CHECK_EQ, -CHECK_NE, CHECK_LE, CHECK_LT, -CHECK_GE, and CHECK_GT. -They compare two values, and log a -FATAL message including the two values when the result is -not as expected. The values must have operator<<(ostream, -...) defined. - -

You may append to the error message like so: - -

-   CHECK_NE(1, 2) << ": The world must be ending!";
-
- -

We are very careful to ensure that each argument is evaluated exactly -once, and that anything which is legal to pass as a function argument is -legal here. In particular, the arguments may be temporary expressions -which will end up being destroyed at the end of the apparent statement, -for example: - -

-   CHECK_EQ(string("abc")[1], 'b');
-
- -

The compiler reports an error if one of the arguments is a -pointer and the other is NULL. To work around this, simply static_cast -NULL to the type of the desired pointer. - -

-   CHECK_EQ(some_ptr, static_cast<SomeType*>(NULL));
-
- -

Better yet, use the CHECK_NOTNULL macro: - -

-   CHECK_NOTNULL(some_ptr);
-   some_ptr->DoSomething();
-
- -

Since this macro returns the given pointer, this is very useful in -constructor initializer lists. - -

-   struct S {
-     S(Something* ptr) : ptr_(CHECK_NOTNULL(ptr)) {}
-     Something* ptr_;
-   };
-
- -

Note that you cannot use this macro as a C++ stream due to this -feature. Please use CHECK_EQ described above to log a -custom message before aborting the application. - -

If you are comparing C strings (char *), a handy set of macros -performs case sensitive as well as case insensitive comparisons - -CHECK_STREQ, CHECK_STRNE, -CHECK_STRCASEEQ, and CHECK_STRCASENE. The -CASE versions are case-insensitive. You can safely pass NULL -pointers for this macro. They treat NULL and any -non-NULL string as not equal. Two NULLs are -equal. - -

Note that both arguments may be temporary strings which are -destructed at the end of the current "full expression" -(e.g., CHECK_STREQ(Foo().c_str(), Bar().c_str()) where -Foo and Bar return C++'s -std::string). - -

The CHECK_DOUBLE_EQ macro checks the equality of two -floating point values, accepting a small error margin. -CHECK_NEAR accepts a third floating point argument, which -specifies the acceptable error margin. - -

Verbose Logging

- -

When you are chasing difficult bugs, thorough log messages are very -useful. However, you may want to ignore too verbose messages in usual -development. For such verbose logging, glog provides the -VLOG macro, which allows you to define your own numeric -logging levels. The --v command line option controls -which verbose messages are logged: - -

-   VLOG(1) << "I'm printed when you run the program with --v=1 or higher";
-   VLOG(2) << "I'm printed when you run the program with --v=2 or higher";
-
- -

With VLOG, the lower the verbose level, the more -likely messages are to be logged. For example, if ---v==1, VLOG(1) will log, but -VLOG(2) will not log. This is opposite of the severity -level, where INFO is 0, and ERROR is 2. ---minloglevel of 1 will log WARNING and -above. Though you can specify any integers for both VLOG -macro and --v flag, the common values for them are small -positive integers. For example, if you write VLOG(0), -you should specify --v=-1 or lower to silence it. This -is less useful since we may not want verbose logs by default in most -cases. The VLOG macros always log at the -INFO log level (when they log at all). - -

Verbose logging can be controlled from the command line on a -per-module basis: - -

-   --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
-
- -

will: - -

    -
  • a. Print VLOG(2) and lower messages from mapreduce.{h,cc} -
  • b. Print VLOG(1) and lower messages from file.{h,cc} -
  • c. Print VLOG(3) and lower messages from files prefixed with "gfs" -
  • d. Print VLOG(0) and lower messages from elsewhere -
- -

The wildcarding functionality shown by (c) supports both '*' -(matches 0 or more characters) and '?' (matches any single character) -wildcards. Please also check the section about command line flags. - -

There's also VLOG_IS_ON(n) "verbose level" condition -macro. This macro returns true when the --v is equal or -greater than n. To be used as - -

-   if (VLOG_IS_ON(2)) {
-     // do some logging preparation and logging
-     // that can't be accomplished with just VLOG(2) << ...;
-   }
-
- -

Verbose level condition macros VLOG_IF, -VLOG_EVERY_N and VLOG_IF_EVERY_N behave -analogous to LOG_IF, LOG_EVERY_N, -LOF_IF_EVERY, but accept a numeric verbosity level as -opposed to a severity level. - -

-   VLOG_IF(1, (size > 1024))
-      << "I'm printed when size is more than 1024 and when you run the "
-         "program with --v=1 or more";
-   VLOG_EVERY_N(1, 10)
-      << "I'm printed every 10th occurrence, and when you run the program "
-         "with --v=1 or more. Present occurence is " << google::COUNTER;
-   VLOG_IF_EVERY_N(1, (size > 1024), 10)
-      << "I'm printed on every 10th occurence of case when size is more "
-         " than 1024, when you run the program with --v=1 or more. ";
-         "Present occurence is " << google::COUNTER;
-
- -

Failure Signal Handler

- -

-The library provides a convenient signal handler that will dump useful -information when the program crashes on certain signals such as SIGSEGV. -The signal handler can be installed by -google::InstallFailureSignalHandler(). The following is an example of output -from the signal handler. - -

-*** Aborted at 1225095260 (unix time) try "date -d @1225095260" if you are using GNU date ***
-*** SIGSEGV (@0x0) received by PID 17711 (TID 0x7f893090a6f0) from PID 0; stack trace: ***
-PC: @           0x412eb1 TestWaitingLogSink::send()
-    @     0x7f892fb417d0 (unknown)
-    @           0x412eb1 TestWaitingLogSink::send()
-    @     0x7f89304f7f06 google::LogMessage::SendToLog()
-    @     0x7f89304f35af google::LogMessage::Flush()
-    @     0x7f89304f3739 google::LogMessage::~LogMessage()
-    @           0x408cf4 TestLogSinkWaitTillSent()
-    @           0x4115de main
-    @     0x7f892f7ef1c4 (unknown)
-    @           0x4046f9 (unknown)
-
- -

-By default, the signal handler writes the failure dump to the standard -error. You can customize the destination by InstallFailureWriter(). - -

Miscellaneous Notes

- -

Performance of Messages

- -

The conditional logging macros provided by glog (e.g., -CHECK, LOG_IF, VLOG, ...) are -carefully implemented and don't execute the right hand side -expressions when the conditions are false. So, the following check -may not sacrifice the performance of your application. - -

-   CHECK(obj.ok) << obj.CreatePrettyFormattedStringButVerySlow();
-
- -

User-defined Failure Function

- -

FATAL severity level messages or unsatisfied -CHECK condition terminate your program. You can change -the behavior of the termination by -InstallFailureFunction. - -

-   void YourFailureFunction() {
-     // Reports something...
-     exit(1);
-   }
-
-   int main(int argc, char* argv[]) {
-     google::InstallFailureFunction(&YourFailureFunction);
-   }
-
- -

By default, glog tries to dump stacktrace and makes the program -exit with status 1. The stacktrace is produced only when you run the -program on an architecture for which glog supports stack tracing (as -of September 2008, glog supports stack tracing for x86 and x86_64). - -

Raw Logging

- -

The header file <glog/raw_logging.h> can be -used for thread-safe logging, which does not allocate any memory or -acquire any locks. Therefore, the macros defined in this -header file can be used by low-level memory allocation and -synchronization code. -Please check src/glog/raw_logging.h.in for detail. -

- -

Google Style perror()

- -

PLOG() and PLOG_IF() and -PCHECK() behave exactly like their LOG* and -CHECK equivalents with the addition that they append a -description of the current state of errno to their output lines. -E.g. - -

-   PCHECK(write(1, NULL, 2) >= 0) << "Write NULL failed";
-
- -

This check fails with the following error message. - -

-   F0825 185142 test.cc:22] Check failed: write(1, NULL, 2) >= 0 Write NULL failed: Bad address [14]
-
- -

Syslog

- -

SYSLOG, SYSLOG_IF, and -SYSLOG_EVERY_N macros are available. -These log to syslog in addition to the normal logs. Be aware that -logging to syslog can drastically impact performance, especially if -syslog is configured for remote logging! Make sure you understand the -implications of outputting to syslog before you use these macros. In -general, it's wise to use these macros sparingly. - -

Strip Logging Messages

- -

Strings used in log messages can increase the size of your binary -and present a privacy concern. You can therefore instruct glog to -remove all strings which fall below a certain severity level by using -the GOOGLE_STRIP_LOG macro: - -

If your application has code like this: - -

-   #define GOOGLE_STRIP_LOG 1    // this must go before the #include!
-   #include <glog/logging.h>
-
- -

The compiler will remove the log messages whose severities are less -than the specified integer value. Since -VLOG logs at the severity level INFO -(numeric value 0), -setting GOOGLE_STRIP_LOG to 1 or greater removes -all log messages associated with VLOGs as well as -INFO log statements. - -

Notes for Windows users

- -

Google glog defines a severity level ERROR, which is -also defined in windows.h . You can make glog not define -INFO, WARNING, ERROR, -and FATAL by defining -GLOG_NO_ABBREVIATED_SEVERITIES before -including glog/logging.h . Even with this macro, you can -still use the iostream like logging facilities: - -

-  #define GLOG_NO_ABBREVIATED_SEVERITIES
-  #include <windows.h>
-  #include <glog/logging.h>
-
-  // ...
-
-  LOG(ERROR) << "This should work";
-  LOG_IF(ERROR, x > y) << "This should be also OK";
-
- -

-However, you cannot -use INFO, WARNING, ERROR, -and FATAL anymore for functions defined -in glog/logging.h . - -

-  #define GLOG_NO_ABBREVIATED_SEVERITIES
-  #include <windows.h>
-  #include <glog/logging.h>
-
-  // ...
-
-  // This won't work.
-  // google::FlushLogFiles(google::ERROR);
-
-  // Use this instead.
-  google::FlushLogFiles(google::GLOG_ERROR);
-
- -

-If you don't need ERROR defined -by windows.h, there are a couple of more workarounds -which sometimes don't work: - -

    -
  • #define WIN32_LEAN_AND_MEAN or NOGDI - before you #include windows.h . -
  • #undef ERROR after you #include - windows.h . -
- -

See -this issue for more detail. - -


-
-Shinichiro Hamaji
-Gregor Hohpe
- -
- - - diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/glog-config.cmake.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/glog-config.cmake.in deleted file mode 100644 index aabdedc3e98..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/glog-config.cmake.in +++ /dev/null @@ -1,11 +0,0 @@ -if (CMAKE_VERSION VERSION_LESS @glog_CMake_VERSION@) - message (FATAL_ERROR "CMake >= @glog_CMake_VERSION@ required") -endif (CMAKE_VERSION VERSION_LESS @glog_CMake_VERSION@) - -@PACKAGE_INIT@ - -include (CMakeFindDependencyMacro) - -@gflags_DEPENDENCY@ - -include ("${CMAKE_CURRENT_LIST_DIR}/glog-targets.cmake") diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/libglog.pc.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/libglog.pc.in deleted file mode 100644 index ad2b0774d89..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/libglog.pc.in +++ /dev/null @@ -1,10 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: libglog -Description: Google Log (glog) C++ logging framework -Version: @VERSION@ -Libs: -L${libdir} -lglog -Cflags: -I${includedir} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_have_attribute.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_have_attribute.m4 deleted file mode 100644 index 19f4021e990..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_have_attribute.m4 +++ /dev/null @@ -1,16 +0,0 @@ -AC_DEFUN([AX_C___ATTRIBUTE__], [ - AC_MSG_CHECKING(for __attribute__) - AC_CACHE_VAL(ac_cv___attribute__, [ - AC_TRY_COMPILE( - [#include - static void foo(void) __attribute__ ((unused)); - void foo(void) { exit(1); }], - [], - ac_cv___attribute__=yes, - ac_cv___attribute__=no - )]) - if test "$ac_cv___attribute__" = "yes"; then - AC_DEFINE(HAVE___ATTRIBUTE__, 1, [define if your compiler has __attribute__]) - fi - AC_MSG_RESULT($ac_cv___attribute__) -]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_have_builtin_expect.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_have_builtin_expect.m4 deleted file mode 100644 index e91b6fd987e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_have_builtin_expect.m4 +++ /dev/null @@ -1,14 +0,0 @@ -AC_DEFUN([AX_C___BUILTIN_EXPECT], [ - AC_MSG_CHECKING(for __builtin_expect) - AC_CACHE_VAL(ac_cv___builtin_expect, [ - AC_TRY_COMPILE( - [int foo(void) { if (__builtin_expect(0, 0)) return 1; return 0; }], - [], - ac_cv___builtin_expect=yes, - ac_cv___builtin_expect=no - )]) - if test "$ac_cv___builtin_expect" = "yes"; then - AC_DEFINE(HAVE___BUILTIN_EXPECT, 1, [define if your compiler has __builtin_expect]) - fi - AC_MSG_RESULT($ac_cv___builtin_expect) -]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_have_sync_val_compare_and_swap.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_have_sync_val_compare_and_swap.m4 deleted file mode 100644 index 88b027e23a2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_have_sync_val_compare_and_swap.m4 +++ /dev/null @@ -1,14 +0,0 @@ -AC_DEFUN([AX_C___SYNC_VAL_COMPARE_AND_SWAP], [ - AC_MSG_CHECKING(for __sync_val_compare_and_swap) - AC_CACHE_VAL(ac_cv___sync_val_compare_and_swap, [ - AC_TRY_LINK( - [], - [int a; if (__sync_val_compare_and_swap(&a, 0, 1)) return 1; return 0;], - ac_cv___sync_val_compare_and_swap=yes, - ac_cv___sync_val_compare_and_swap=no - )]) - if test "$ac_cv___sync_val_compare_and_swap" = "yes"; then - AC_DEFINE(HAVE___SYNC_VAL_COMPARE_AND_SWAP, 1, [define if your compiler has __sync_val_compare_and_swap]) - fi - AC_MSG_RESULT($ac_cv___sync_val_compare_and_swap) -]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_rwlock.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_rwlock.m4 deleted file mode 100644 index 5065bcc1c5c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ac_rwlock.m4 +++ /dev/null @@ -1,31 +0,0 @@ -# TODO(csilvers): it would be better to actually try to link against -# -pthreads, to make sure it defines these methods, but that may be -# too hard, since pthread support is really tricky. - -# Check for support for pthread_rwlock_init() etc. -# These aren't posix, but are widely supported. To get them on linux, -# you need to define _XOPEN_SOURCE first, so this check assumes your -# application does that. -# -# Note: OS X (as of 6/1/06) seems to support pthread_rwlock, but -# doesn't define PTHREAD_RWLOCK_INITIALIZER. Therefore, we don't test -# that particularly macro. It's probably best if you don't use that -# macro in your code either. - -AC_DEFUN([AC_RWLOCK], -[AC_CACHE_CHECK(support for pthread_rwlock_* functions, -ac_cv_rwlock, -[AC_LANG_SAVE - AC_LANG_C - AC_TRY_COMPILE([#define _XOPEN_SOURCE 500 - #include ], - [pthread_rwlock_t l; pthread_rwlock_init(&l, NULL); - pthread_rwlock_rdlock(&l); - return 0;], - ac_cv_rwlock=yes, ac_cv_rwlock=no) - AC_LANG_RESTORE -]) -if test "$ac_cv_rwlock" = yes; then - AC_DEFINE(HAVE_RWLOCK,1,[define if the compiler implements pthread_rwlock_*]) -fi -]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/acx_pthread.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/acx_pthread.m4 deleted file mode 100644 index 2cf20de144a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/acx_pthread.m4 +++ /dev/null @@ -1,363 +0,0 @@ -# This was retrieved from -# http://svn.0pointer.de/viewvc/trunk/common/acx_pthread.m4?revision=1277&root=avahi -# See also (perhaps for new versions?) -# http://svn.0pointer.de/viewvc/trunk/common/acx_pthread.m4?root=avahi -# -# We've rewritten the inconsistency check code (from avahi), to work -# more broadly. In particular, it no longer assumes ld accepts -zdefs. -# This caused a restructing of the code, but the functionality has only -# changed a little. - -dnl @synopsis ACX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]]) -dnl -dnl @summary figure out how to build C programs using POSIX threads -dnl -dnl This macro figures out how to build C programs using POSIX threads. -dnl It sets the PTHREAD_LIBS output variable to the threads library and -dnl linker flags, and the PTHREAD_CFLAGS output variable to any special -dnl C compiler flags that are needed. (The user can also force certain -dnl compiler flags/libs to be tested by setting these environment -dnl variables.) -dnl -dnl Also sets PTHREAD_CC to any special C compiler that is needed for -dnl multi-threaded programs (defaults to the value of CC otherwise). -dnl (This is necessary on AIX to use the special cc_r compiler alias.) -dnl -dnl NOTE: You are assumed to not only compile your program with these -dnl flags, but also link it with them as well. e.g. you should link -dnl with $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS -dnl $LIBS -dnl -dnl If you are only building threads programs, you may wish to use -dnl these variables in your default LIBS, CFLAGS, and CC: -dnl -dnl LIBS="$PTHREAD_LIBS $LIBS" -dnl CFLAGS="$CFLAGS $PTHREAD_CFLAGS" -dnl CC="$PTHREAD_CC" -dnl -dnl In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute -dnl constant has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to -dnl that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX). -dnl -dnl ACTION-IF-FOUND is a list of shell commands to run if a threads -dnl library is found, and ACTION-IF-NOT-FOUND is a list of commands to -dnl run it if it is not found. If ACTION-IF-FOUND is not specified, the -dnl default action will define HAVE_PTHREAD. -dnl -dnl Please let the authors know if this macro fails on any platform, or -dnl if you have any other suggestions or comments. This macro was based -dnl on work by SGJ on autoconf scripts for FFTW (www.fftw.org) (with -dnl help from M. Frigo), as well as ac_pthread and hb_pthread macros -dnl posted by Alejandro Forero Cuervo to the autoconf macro repository. -dnl We are also grateful for the helpful feedback of numerous users. -dnl -dnl @category InstalledPackages -dnl @author Steven G. Johnson -dnl @version 2006-05-29 -dnl @license GPLWithACException -dnl -dnl Checks for GCC shared/pthread inconsistency based on work by -dnl Marcin Owsiany - - -AC_DEFUN([ACX_PTHREAD], [ -AC_REQUIRE([AC_CANONICAL_HOST]) -AC_LANG_SAVE -AC_LANG_C -acx_pthread_ok=no - -# We used to check for pthread.h first, but this fails if pthread.h -# requires special compiler flags (e.g. on True64 or Sequent). -# It gets checked for in the link test anyway. - -# First of all, check if the user has set any of the PTHREAD_LIBS, -# etcetera environment variables, and if threads linking works using -# them: -if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then - save_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS $PTHREAD_CFLAGS" - save_LIBS="$LIBS" - LIBS="$PTHREAD_LIBS $LIBS" - AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS]) - AC_TRY_LINK_FUNC(pthread_join, acx_pthread_ok=yes) - AC_MSG_RESULT($acx_pthread_ok) - if test x"$acx_pthread_ok" = xno; then - PTHREAD_LIBS="" - PTHREAD_CFLAGS="" - fi - LIBS="$save_LIBS" - CFLAGS="$save_CFLAGS" -fi - -# We must check for the threads library under a number of different -# names; the ordering is very important because some systems -# (e.g. DEC) have both -lpthread and -lpthreads, where one of the -# libraries is broken (non-POSIX). - -# Create a list of thread flags to try. Items starting with a "-" are -# C compiler flags, and other items are library names, except for "none" -# which indicates that we try without any flags at all, and "pthread-config" -# which is a program returning the flags for the Pth emulation library. - -acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config" - -# The ordering *is* (sometimes) important. Some notes on the -# individual items follow: - -# pthreads: AIX (must check this before -lpthread) -# none: in case threads are in libc; should be tried before -Kthread and -# other compiler flags to prevent continual compiler warnings -# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h) -# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able) -# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread) -# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads) -# -pthreads: Solaris/gcc -# -mthreads: Mingw32/gcc, Lynx/gcc -# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it -# doesn't hurt to check since this sometimes defines pthreads too; -# also defines -D_REENTRANT) -# ... -mt is also the pthreads flag for HP/aCC -# pthread: Linux, etcetera -# --thread-safe: KAI C++ -# pthread-config: use pthread-config program (for GNU Pth library) - -case "${host_cpu}-${host_os}" in - *solaris*) - - # On Solaris (at least, for some versions), libc contains stubbed - # (non-functional) versions of the pthreads routines, so link-based - # tests will erroneously succeed. (We need to link with -pthreads/-mt/ - # -lpthread.) (The stubs are missing pthread_cleanup_push, or rather - # a function called by this macro, so we could check for that, but - # who knows whether they'll stub that too in a future libc.) So, - # we'll just look for -pthreads and -lpthread first: - - acx_pthread_flags="-pthreads pthread -mt -pthread $acx_pthread_flags" - ;; -esac - -if test x"$acx_pthread_ok" = xno; then -for flag in $acx_pthread_flags; do - - case $flag in - none) - AC_MSG_CHECKING([whether pthreads work without any flags]) - ;; - - -*) - AC_MSG_CHECKING([whether pthreads work with $flag]) - PTHREAD_CFLAGS="$flag" - ;; - - pthread-config) - AC_CHECK_PROG(acx_pthread_config, pthread-config, yes, no) - if test x"$acx_pthread_config" = xno; then continue; fi - PTHREAD_CFLAGS="`pthread-config --cflags`" - PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`" - ;; - - *) - AC_MSG_CHECKING([for the pthreads library -l$flag]) - PTHREAD_LIBS="-l$flag" - ;; - esac - - save_LIBS="$LIBS" - save_CFLAGS="$CFLAGS" - LIBS="$PTHREAD_LIBS $LIBS" - CFLAGS="$CFLAGS $PTHREAD_CFLAGS" - - # Check for various functions. We must include pthread.h, - # since some functions may be macros. (On the Sequent, we - # need a special flag -Kthread to make this header compile.) - # We check for pthread_join because it is in -lpthread on IRIX - # while pthread_create is in libc. We check for pthread_attr_init - # due to DEC craziness with -lpthreads. We check for - # pthread_cleanup_push because it is one of the few pthread - # functions on Solaris that doesn't have a non-functional libc stub. - # We try pthread_create on general principles. - AC_TRY_LINK([#include ], - [pthread_t th; pthread_join(th, 0); - pthread_attr_init(0); pthread_cleanup_push(0, 0); - pthread_create(0,0,0,0); pthread_cleanup_pop(0); ], - [acx_pthread_ok=yes]) - - LIBS="$save_LIBS" - CFLAGS="$save_CFLAGS" - - AC_MSG_RESULT($acx_pthread_ok) - if test "x$acx_pthread_ok" = xyes; then - break; - fi - - PTHREAD_LIBS="" - PTHREAD_CFLAGS="" -done -fi - -# Various other checks: -if test "x$acx_pthread_ok" = xyes; then - save_LIBS="$LIBS" - LIBS="$PTHREAD_LIBS $LIBS" - save_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS $PTHREAD_CFLAGS" - - # Detect AIX lossage: JOINABLE attribute is called UNDETACHED. - AC_MSG_CHECKING([for joinable pthread attribute]) - attr_name=unknown - for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do - AC_TRY_LINK([#include ], [int attr=$attr; return attr;], - [attr_name=$attr; break]) - done - AC_MSG_RESULT($attr_name) - if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then - AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name, - [Define to necessary symbol if this constant - uses a non-standard name on your system.]) - fi - - AC_MSG_CHECKING([if more special flags are required for pthreads]) - flag=no - case "${host_cpu}-${host_os}" in - *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";; - *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";; - esac - AC_MSG_RESULT(${flag}) - if test "x$flag" != xno; then - PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS" - fi - - LIBS="$save_LIBS" - CFLAGS="$save_CFLAGS" - # More AIX lossage: must compile with xlc_r or cc_r - if test x"$GCC" != xyes; then - AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC}) - else - PTHREAD_CC=$CC - fi - - # The next part tries to detect GCC inconsistency with -shared on some - # architectures and systems. The problem is that in certain - # configurations, when -shared is specified, GCC "forgets" to - # internally use various flags which are still necessary. - - # - # Prepare the flags - # - save_CFLAGS="$CFLAGS" - save_LIBS="$LIBS" - save_CC="$CC" - - # Try with the flags determined by the earlier checks. - # - # -Wl,-z,defs forces link-time symbol resolution, so that the - # linking checks with -shared actually have any value - # - # FIXME: -fPIC is required for -shared on many architectures, - # so we specify it here, but the right way would probably be to - # properly detect whether it is actually required. - CFLAGS="-shared -fPIC -Wl,-z,defs $CFLAGS $PTHREAD_CFLAGS" - LIBS="$PTHREAD_LIBS $LIBS" - CC="$PTHREAD_CC" - - # In order not to create several levels of indentation, we test - # the value of "$done" until we find the cure or run out of ideas. - done="no" - - # First, make sure the CFLAGS we added are actually accepted by our - # compiler. If not (and OS X's ld, for instance, does not accept -z), - # then we can't do this test. - if test x"$done" = xno; then - AC_MSG_CHECKING([whether to check for GCC pthread/shared inconsistencies]) - AC_TRY_LINK(,, , [done=yes]) - - if test "x$done" = xyes ; then - AC_MSG_RESULT([no]) - else - AC_MSG_RESULT([yes]) - fi - fi - - if test x"$done" = xno; then - AC_MSG_CHECKING([whether -pthread is sufficient with -shared]) - AC_TRY_LINK([#include ], - [pthread_t th; pthread_join(th, 0); - pthread_attr_init(0); pthread_cleanup_push(0, 0); - pthread_create(0,0,0,0); pthread_cleanup_pop(0); ], - [done=yes]) - - if test "x$done" = xyes; then - AC_MSG_RESULT([yes]) - else - AC_MSG_RESULT([no]) - fi - fi - - # - # Linux gcc on some architectures such as mips/mipsel forgets - # about -lpthread - # - if test x"$done" = xno; then - AC_MSG_CHECKING([whether -lpthread fixes that]) - LIBS="-lpthread $PTHREAD_LIBS $save_LIBS" - AC_TRY_LINK([#include ], - [pthread_t th; pthread_join(th, 0); - pthread_attr_init(0); pthread_cleanup_push(0, 0); - pthread_create(0,0,0,0); pthread_cleanup_pop(0); ], - [done=yes]) - - if test "x$done" = xyes; then - AC_MSG_RESULT([yes]) - PTHREAD_LIBS="-lpthread $PTHREAD_LIBS" - else - AC_MSG_RESULT([no]) - fi - fi - # - # FreeBSD 4.10 gcc forgets to use -lc_r instead of -lc - # - if test x"$done" = xno; then - AC_MSG_CHECKING([whether -lc_r fixes that]) - LIBS="-lc_r $PTHREAD_LIBS $save_LIBS" - AC_TRY_LINK([#include ], - [pthread_t th; pthread_join(th, 0); - pthread_attr_init(0); pthread_cleanup_push(0, 0); - pthread_create(0,0,0,0); pthread_cleanup_pop(0); ], - [done=yes]) - - if test "x$done" = xyes; then - AC_MSG_RESULT([yes]) - PTHREAD_LIBS="-lc_r $PTHREAD_LIBS" - else - AC_MSG_RESULT([no]) - fi - fi - if test x"$done" = xno; then - # OK, we have run out of ideas - AC_MSG_WARN([Impossible to determine how to use pthreads with shared libraries]) - - # so it's not safe to assume that we may use pthreads - acx_pthread_ok=no - fi - - CFLAGS="$save_CFLAGS" - LIBS="$save_LIBS" - CC="$save_CC" -else - PTHREAD_CC="$CC" -fi - -AC_SUBST(PTHREAD_LIBS) -AC_SUBST(PTHREAD_CFLAGS) -AC_SUBST(PTHREAD_CC) - -# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND: -if test x"$acx_pthread_ok" = xyes; then - ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1]) - : -else - acx_pthread_ok=no - $2 -fi -AC_LANG_RESTORE -])dnl ACX_PTHREAD diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/google_namespace.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/google_namespace.m4 deleted file mode 100644 index 79e0a6d42a6..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/google_namespace.m4 +++ /dev/null @@ -1,36 +0,0 @@ -# Allow users to override the namespace we define our application's classes in -# Arg $1 is the default namespace to use if --enable-namespace isn't present. - -# In general, $1 should be 'google', so we put all our exported symbols in a -# unique namespace that is not likely to conflict with anyone else. However, -# when it makes sense -- for instance, when publishing stl-like code -- you -# may want to go with a different default, like 'std'. - -AC_DEFUN([AC_DEFINE_GOOGLE_NAMESPACE], - [google_namespace_default=[$1] - AC_ARG_ENABLE(namespace, [ --enable-namespace=FOO to define these Google - classes in the FOO namespace. --disable-namespace - to define them in the global namespace. Default - is to define them in namespace $1.], - [case "$enableval" in - yes) google_namespace="$google_namespace_default" ;; - no) google_namespace="" ;; - *) google_namespace="$enableval" ;; - esac], - [google_namespace="$google_namespace_default"]) - if test -n "$google_namespace"; then - ac_google_namespace="$google_namespace" - ac_google_start_namespace="namespace $google_namespace {" - ac_google_end_namespace="}" - else - ac_google_namespace="" - ac_google_start_namespace="" - ac_google_end_namespace="" - fi - AC_DEFINE_UNQUOTED(GOOGLE_NAMESPACE, $ac_google_namespace, - Namespace for Google classes) - AC_DEFINE_UNQUOTED(_START_GOOGLE_NAMESPACE_, $ac_google_start_namespace, - Puts following code inside the Google namespace) - AC_DEFINE_UNQUOTED(_END_GOOGLE_NAMESPACE_, $ac_google_end_namespace, - Stops putting the code inside the Google namespace) -]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ltsugar.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ltsugar.m4 deleted file mode 100644 index 9000a057d31..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/ltsugar.m4 +++ /dev/null @@ -1,123 +0,0 @@ -# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- -# -# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc. -# Written by Gary V. Vaughan, 2004 -# -# This file is free software; the Free Software Foundation gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. - -# serial 6 ltsugar.m4 - -# This is to help aclocal find these macros, as it can't see m4_define. -AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) - - -# lt_join(SEP, ARG1, [ARG2...]) -# ----------------------------- -# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their -# associated separator. -# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier -# versions in m4sugar had bugs. -m4_define([lt_join], -[m4_if([$#], [1], [], - [$#], [2], [[$2]], - [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) -m4_define([_lt_join], -[m4_if([$#$2], [2], [], - [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) - - -# lt_car(LIST) -# lt_cdr(LIST) -# ------------ -# Manipulate m4 lists. -# These macros are necessary as long as will still need to support -# Autoconf-2.59 which quotes differently. -m4_define([lt_car], [[$1]]) -m4_define([lt_cdr], -[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], - [$#], 1, [], - [m4_dquote(m4_shift($@))])]) -m4_define([lt_unquote], $1) - - -# lt_append(MACRO-NAME, STRING, [SEPARATOR]) -# ------------------------------------------ -# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'. -# Note that neither SEPARATOR nor STRING are expanded; they are appended -# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). -# No SEPARATOR is output if MACRO-NAME was previously undefined (different -# than defined and empty). -# -# This macro is needed until we can rely on Autoconf 2.62, since earlier -# versions of m4sugar mistakenly expanded SEPARATOR but not STRING. -m4_define([lt_append], -[m4_define([$1], - m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) - - - -# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) -# ---------------------------------------------------------- -# Produce a SEP delimited list of all paired combinations of elements of -# PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list -# has the form PREFIXmINFIXSUFFIXn. -# Needed until we can rely on m4_combine added in Autoconf 2.62. -m4_define([lt_combine], -[m4_if(m4_eval([$# > 3]), [1], - [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl -[[m4_foreach([_Lt_prefix], [$2], - [m4_foreach([_Lt_suffix], - ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, - [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) - - -# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) -# ----------------------------------------------------------------------- -# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited -# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. -m4_define([lt_if_append_uniq], -[m4_ifdef([$1], - [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], - [lt_append([$1], [$2], [$3])$4], - [$5])], - [lt_append([$1], [$2], [$3])$4])]) - - -# lt_dict_add(DICT, KEY, VALUE) -# ----------------------------- -m4_define([lt_dict_add], -[m4_define([$1($2)], [$3])]) - - -# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) -# -------------------------------------------- -m4_define([lt_dict_add_subkey], -[m4_define([$1($2:$3)], [$4])]) - - -# lt_dict_fetch(DICT, KEY, [SUBKEY]) -# ---------------------------------- -m4_define([lt_dict_fetch], -[m4_ifval([$3], - m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), - m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) - - -# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) -# ----------------------------------------------------------------- -m4_define([lt_if_dict_fetch], -[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], - [$5], - [$6])]) - - -# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) -# -------------------------------------------------------------- -m4_define([lt_dict_filter], -[m4_if([$5], [], [], - [lt_join(m4_quote(m4_default([$4], [[, ]])), - lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), - [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl -]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/lt~obsolete.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/lt~obsolete.m4 deleted file mode 100644 index c573da90c5c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/lt~obsolete.m4 +++ /dev/null @@ -1,98 +0,0 @@ -# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- -# -# Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc. -# Written by Scott James Remnant, 2004. -# -# This file is free software; the Free Software Foundation gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. - -# serial 5 lt~obsolete.m4 - -# These exist entirely to fool aclocal when bootstrapping libtool. -# -# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN) -# which have later been changed to m4_define as they aren't part of the -# exported API, or moved to Autoconf or Automake where they belong. -# -# The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN -# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us -# using a macro with the same name in our local m4/libtool.m4 it'll -# pull the old libtool.m4 in (it doesn't see our shiny new m4_define -# and doesn't know about Autoconf macros at all.) -# -# So we provide this file, which has a silly filename so it's always -# included after everything else. This provides aclocal with the -# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything -# because those macros already exist, or will be overwritten later. -# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. -# -# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. -# Yes, that means every name once taken will need to remain here until -# we give up compatibility with versions before 1.7, at which point -# we need to keep only those names which we still refer to. - -# This is to help aclocal find these macros, as it can't see m4_define. -AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) - -m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) -m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) -m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) -m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) -m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) -m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) -m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) -m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) -m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) -m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) -m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) -m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) -m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) -m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) -m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) -m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) -m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) -m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) -m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) -m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) -m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) -m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) -m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) -m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) -m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) -m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) -m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) -m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) -m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) -m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) -m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) -m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) -m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) -m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) -m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) -m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) -m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) -m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) -m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) -m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) -m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) -m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) -m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) -m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) -m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) -m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) -m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) -m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) -m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) -m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) -m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) -m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) -m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) -m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) -m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])]) -m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])]) -m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])]) -m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])]) -m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])]) -m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])]) -m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/namespaces.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/namespaces.m4 deleted file mode 100644 index d78dbe4cc2e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/namespaces.m4 +++ /dev/null @@ -1,15 +0,0 @@ -# Checks whether the compiler implements namespaces -AC_DEFUN([AC_CXX_NAMESPACES], - [AC_CACHE_CHECK(whether the compiler implements namespaces, - ac_cv_cxx_namespaces, - [AC_LANG_SAVE - AC_LANG_CPLUSPLUS - AC_TRY_COMPILE([namespace Outer { - namespace Inner { int i = 0; }}], - [using namespace Outer::Inner; return i;], - ac_cv_cxx_namespaces=yes, - ac_cv_cxx_namespaces=no) - AC_LANG_RESTORE]) - if test "$ac_cv_cxx_namespaces" = yes; then - AC_DEFINE(HAVE_NAMESPACES, 1, [define if the compiler implements namespaces]) - fi]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/pc_from_ucontext.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/pc_from_ucontext.m4 deleted file mode 100644 index daffddb536f..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/pc_from_ucontext.m4 +++ /dev/null @@ -1,71 +0,0 @@ -# We want to access the "PC" (Program Counter) register from a struct -# ucontext. Every system has its own way of doing that. We try all the -# possibilities we know about. Note REG_PC should come first (REG_RIP -# is also defined on solaris, but does the wrong thing). - -# OpenBSD doesn't have ucontext.h, but we can get PC from ucontext_t -# by using signal.h. - -# The first argument of AC_PC_FROM_UCONTEXT will be invoked when we -# cannot find a way to obtain PC from ucontext. - -AC_DEFUN([AC_PC_FROM_UCONTEXT], - [AC_CHECK_HEADERS(ucontext.h) - AC_CHECK_HEADERS(sys/ucontext.h) # ucontext on OS X 10.6 (at least) - AC_MSG_CHECKING([how to access the program counter from a struct ucontext]) - pc_fields=" uc_mcontext.gregs[[REG_PC]]" # Solaris x86 (32 + 64 bit) - pc_fields="$pc_fields uc_mcontext.gregs[[REG_EIP]]" # Linux (i386) - pc_fields="$pc_fields uc_mcontext.gregs[[REG_RIP]]" # Linux (x86_64) - pc_fields="$pc_fields uc_mcontext.sc_ip" # Linux (ia64) - pc_fields="$pc_fields uc_mcontext.uc_regs->gregs[[PT_NIP]]" # Linux (ppc) - pc_fields="$pc_fields uc_mcontext.gregs[[R15]]" # Linux (arm old [untested]) - pc_fields="$pc_fields uc_mcontext.arm_pc" # Linux (arm new [untested]) - pc_fields="$pc_fields uc_mcontext.mc_eip" # FreeBSD (i386) - pc_fields="$pc_fields uc_mcontext.mc_rip" # FreeBSD (x86_64 [untested]) - pc_fields="$pc_fields uc_mcontext.__gregs[[_REG_EIP]]" # NetBSD (i386) - pc_fields="$pc_fields uc_mcontext.__gregs[[_REG_RIP]]" # NetBSD (x86_64) - pc_fields="$pc_fields uc_mcontext->ss.eip" # OS X (i386, <=10.4) - pc_fields="$pc_fields uc_mcontext->__ss.__eip" # OS X (i386, >=10.5) - pc_fields="$pc_fields uc_mcontext->ss.rip" # OS X (x86_64) - pc_fields="$pc_fields uc_mcontext->__ss.__rip" # OS X (>=10.5 [untested]) - pc_fields="$pc_fields uc_mcontext->ss.srr0" # OS X (ppc, ppc64 [untested]) - pc_fields="$pc_fields uc_mcontext->__ss.__srr0" # OS X (>=10.5 [untested]) - pc_field_found=false - for pc_field in $pc_fields; do - if ! $pc_field_found; then - if test "x$ac_cv_header_sys_ucontext_h" = xyes; then - AC_TRY_COMPILE([#define _GNU_SOURCE 1 - #include ], - [ucontext_t u; return u.$pc_field == 0;], - AC_DEFINE_UNQUOTED(PC_FROM_UCONTEXT, $pc_field, - How to access the PC from a struct ucontext) - AC_MSG_RESULT([$pc_field]) - pc_field_found=true) - else - AC_TRY_COMPILE([#define _GNU_SOURCE 1 - #include ], - [ucontext_t u; return u.$pc_field == 0;], - AC_DEFINE_UNQUOTED(PC_FROM_UCONTEXT, $pc_field, - How to access the PC from a struct ucontext) - AC_MSG_RESULT([$pc_field]) - pc_field_found=true) - fi - fi - done - if ! $pc_field_found; then - pc_fields=" sc_eip" # OpenBSD (i386) - pc_fields="$pc_fields sc_rip" # OpenBSD (x86_64) - for pc_field in $pc_fields; do - if ! $pc_field_found; then - AC_TRY_COMPILE([#include ], - [ucontext_t u; return u.$pc_field == 0;], - AC_DEFINE_UNQUOTED(PC_FROM_UCONTEXT, $pc_field, - How to access the PC from a struct ucontext) - AC_MSG_RESULT([$pc_field]) - pc_field_found=true) - fi - done - fi - if ! $pc_field_found; then - [$1] - fi]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/stl_namespace.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/stl_namespace.m4 deleted file mode 100644 index 989ad80696a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/stl_namespace.m4 +++ /dev/null @@ -1,25 +0,0 @@ -# We check what namespace stl code like vector expects to be executed in - -AC_DEFUN([AC_CXX_STL_NAMESPACE], - [AC_CACHE_CHECK( - what namespace STL code is in, - ac_cv_cxx_stl_namespace, - [AC_REQUIRE([AC_CXX_NAMESPACES]) - AC_LANG_SAVE - AC_LANG_CPLUSPLUS - AC_TRY_COMPILE([#include ], - [vector t; return 0;], - ac_cv_cxx_stl_namespace=none) - AC_TRY_COMPILE([#include ], - [std::vector t; return 0;], - ac_cv_cxx_stl_namespace=std) - AC_LANG_RESTORE]) - if test "$ac_cv_cxx_stl_namespace" = none; then - AC_DEFINE(STL_NAMESPACE,, - [the namespace where STL code like vector<> is defined]) - fi - if test "$ac_cv_cxx_stl_namespace" = std; then - AC_DEFINE(STL_NAMESPACE,std, - [the namespace where STL code like vector<> is defined]) - fi -]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/using_operator.m4 b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/using_operator.m4 deleted file mode 100644 index 95a9951eb34..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/m4/using_operator.m4 +++ /dev/null @@ -1,15 +0,0 @@ -AC_DEFUN([AC_CXX_USING_OPERATOR], - [AC_CACHE_CHECK( - whether compiler supports using ::operator<<, - ac_cv_cxx_using_operator, - [AC_LANG_SAVE - AC_LANG_CPLUSPLUS - AC_TRY_COMPILE([#include - std::ostream& operator<<(std::ostream&, struct s);], - [using ::operator<<; return 0;], - ac_cv_cxx_using_operator=1, - ac_cv_cxx_using_operator=0) - AC_LANG_RESTORE]) - if test "$ac_cv_cxx_using_operator" = 1; then - AC_DEFINE(HAVE_USING_OPERATOR, 1, [define if the compiler supports using expression for operator]) - fi]) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb.sh deleted file mode 100755 index a1cdf321ef5..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb.sh +++ /dev/null @@ -1,73 +0,0 @@ -#!/bin/bash -e - -# This takes one commandline argument, the name of the package. If no -# name is given, then we'll end up just using the name associated with -# an arbitrary .tar.gz file in the rootdir. That's fine: there's probably -# only one. -# -# Run this from the 'packages' directory, just under rootdir - -## Set LIB to lib if exporting a library, empty-string else -LIB= -#LIB=lib - -PACKAGE="$1" -VERSION="$2" - -# We can only build Debian packages, if the Debian build tools are installed -if [ \! -x /usr/bin/debuild ]; then - echo "Cannot find /usr/bin/debuild. Not building Debian packages." 1>&2 - exit 0 -fi - -# Double-check we're in the packages directory, just under rootdir -if [ \! -r ../Makefile -a \! -r ../INSTALL ]; then - echo "Must run $0 in the 'packages' directory, under the root directory." 1>&2 - echo "Also, you must run \"make dist\" before running this script." 1>&2 - exit 0 -fi - -# Find the top directory for this package -topdir="${PWD%/*}" - -# Find the tar archive built by "make dist" -archive="$PACKAGE-$VERSION" -if [ -z "${archive}" ]; then - echo "Cannot find ../$PACKAGE*.tar.gz. Run \"make dist\" first." 1>&2 - exit 0 -fi - -# Create a pristine directory for building the Debian package files -trap 'rm -rf '`pwd`/tmp'; exit $?' EXIT SIGHUP SIGINT SIGTERM - -rm -rf tmp -mkdir -p tmp -cd tmp - -package="google-glog_$VERSION" - -# Debian has very specific requirements about the naming of build -# directories, and tar archives. It also wants to write all generated -# packages to the parent of the source directory. We accommodate these -# requirements by building directly from the tar file. -ln -s "${topdir}/${archive}.tar.gz" "${LIB}${package}.orig.tar.gz" -tar zfx "${LIB}${package}.orig.tar.gz" -mv "${archive}" "${LIB}${package}" -cd "${LIB}${package}" -# This is one of those 'specific requirements': where the deb control files live -cp -a "packages/deb" "debian" - -# Now, we can call Debian's standard build tool -debuild -uc -us -cd ../.. # get back to the original top-level dir - -# We'll put the result in a subdirectory that's named after the OS version -# we've made this .deb file for. -destdir="debian-$(cat /etc/debian_version 2>/dev/null || echo UNKNOWN)" - -rm -rf "$destdir" -mkdir -p "$destdir" -mv $(find tmp -mindepth 1 -maxdepth 1 -type f) "$destdir" - -echo -echo "The Debian package files are located in $PWD/$destdir" diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/README b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/README deleted file mode 100644 index 57becfda757..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/README +++ /dev/null @@ -1,7 +0,0 @@ -The list of files here isn't complete. For a step-by-step guide on -how to set this package up correctly, check out - http://www.debian.org/doc/maint-guide/ - -Most of the files that are in this directory are boilerplate. -However, you may need to change the list of binary-arch dependencies -in 'rules'. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/changelog b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/changelog deleted file mode 100644 index 4cbed1bd0cd..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/changelog +++ /dev/null @@ -1,71 +0,0 @@ -google-glog (0.4.0-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Tue, 22 Jan 2019 21:00:26 +0900 - -google-glog (0.3.5-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Tue, 09 May 2017 16:22:12 +0900 - -google-glog (0.3.4-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Tue, 10 Mar 2015 12:02:20 +0900 - -google-glog (0.3.3-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Fri, 01 Feb 2012 14:54:14 +0900 - -google-glog (0.3.2-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Thu, 12 Jan 2012 17:36:14 +0900 - -google-glog (0.3.1-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Tue, 15 Jun 2010 13:50:47 +0900 - -google-glog (0.3-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Thu, 30 Jul 2009 21:31:35 +0900 - -google-glog (0.2.1-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Fri, 10 Apr 2009 15:24:17 +0900 - -google-glog (0.2-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Fri, 23 Jan 2009 03:14:29 +0900 - -google-glog (0.1.2-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Tue, 18 Nov 2008 20:37:00 +0900 - -google-glog (0.1.1-1) unstable; urgency=low - - * New upstream release. - - -- Google Inc. Wed, 15 Oct 2008 20:38:19 +0900 - -google-glog (0.1-1) unstable; urgency=low - - * Initial release. - - -- Google Inc. Sat, 10 May 2008 12:31:10 +0900 diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/compat b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/compat deleted file mode 100644 index b8626c4cff2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/compat +++ /dev/null @@ -1 +0,0 @@ -4 diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/control b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/control deleted file mode 100644 index 110a72cb356..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/control +++ /dev/null @@ -1,23 +0,0 @@ -Source: google-glog -Priority: optional -Maintainer: Google Inc. -Build-Depends: debhelper (>= 4.0.0), binutils -Standards-Version: 3.6.1 - -Package: libgoogle-glog-dev -Section: libdevel -Architecture: any -Depends: libgoogle-glog0 (= ${Source-Version}) -Description: a library that implements application-level logging. - This library provides logging APIs based on C++-style streams and - various helper macros. The devel package contains static and debug - libraries and header files for developing applications that use the - google-glog package. - -Package: libgoogle-glog0 -Section: libs -Architecture: any -Depends: ${shlibs:Depends} -Description: a library that implements application-level logging. - This library provides logging APIs based on C++-style streams and - various helper macros. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/copyright b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/copyright deleted file mode 100644 index b2ce8e8f023..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/copyright +++ /dev/null @@ -1,35 +0,0 @@ -This package was debianized by Google Inc. on -13 June 2008. - -It was downloaded from https://github.com/google/glog - -Upstream Author: opensource@google.com - -Copyright (c) 2008, Google Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/docs b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/docs deleted file mode 100644 index 6da25d4d311..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/docs +++ /dev/null @@ -1,7 +0,0 @@ -AUTHORS -COPYING -ChangeLog -INSTALL -README.md -doc/designstyle.css -doc/glog.html diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog-dev.dirs b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog-dev.dirs deleted file mode 100644 index bddfbf5c112..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog-dev.dirs +++ /dev/null @@ -1,4 +0,0 @@ -usr/lib -usr/lib/pkgconfig -usr/include -usr/include/glog diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog-dev.install b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog-dev.install deleted file mode 100644 index 9c61e86eaf6..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog-dev.install +++ /dev/null @@ -1,10 +0,0 @@ -usr/include/glog/* -usr/lib/lib*.so -usr/lib/lib*.a -usr/lib/*.la -usr/lib/pkgconfig/* -debian/tmp/usr/include/glog/* -debian/tmp/usr/lib/lib*.so -debian/tmp/usr/lib/lib*.a -debian/tmp/usr/lib/*.la -debian/tmp/usr/lib/pkgconfig/* diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog0.dirs b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog0.dirs deleted file mode 100644 index 68457717bd8..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog0.dirs +++ /dev/null @@ -1 +0,0 @@ -usr/lib diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog0.install b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog0.install deleted file mode 100644 index 704ea87ab75..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/libgoogle-glog0.install +++ /dev/null @@ -1,2 +0,0 @@ -usr/lib/lib*.so.* -debian/tmp/usr/lib/lib*.so.* diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/rules b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/rules deleted file mode 100755 index f520befd259..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/deb/rules +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/make -f -# -*- makefile -*- -# Sample debian/rules that uses debhelper. -# This file was originally written by Joey Hess and Craig Small. -# As a special exception, when this file is copied by dh-make into a -# dh-make output file, you may use that output file without restriction. -# This special exception was added by Craig Small in version 0.37 of dh-make. - -# Uncomment this to turn on verbose mode. -#export DH_VERBOSE=1 - - -# These are used for cross-compiling and for saving the configure script -# from having to guess our platform (since we know it already) -DEB_HOST_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE) -DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE) - - -CFLAGS = -Wall -g - -ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS))) - CFLAGS += -O0 -else - CFLAGS += -O2 -endif -ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS))) - INSTALL_PROGRAM += -s -endif - -# shared library versions, option 1 -#version=2.0.5 -#major=2 -# option 2, assuming the library is created as src/.libs/libfoo.so.2.0.5 or so -version=`ls src/.libs/lib*.so.* | \ - awk '{if (match($$0,/[0-9]+\.[0-9]+\.[0-9]+$$/)) print substr($$0,RSTART)}'` -major=`ls src/.libs/lib*.so.* | \ - awk '{if (match($$0,/\.so\.[0-9]+$$/)) print substr($$0,RSTART+4)}'` - -config.status: configure - dh_testdir - # Add here commands to configure the package. - CFLAGS="$(CFLAGS)" ./configure --host=$(DEB_HOST_GNU_TYPE) --build=$(DEB_BUILD_GNU_TYPE) --prefix=/usr --mandir=\$${prefix}/share/man --infodir=\$${prefix}/share/info - - -build: build-stamp -build-stamp: config.status - dh_testdir - - # Add here commands to compile the package. - $(MAKE) - - touch build-stamp - -clean: - dh_testdir - dh_testroot - rm -f build-stamp - - # Add here commands to clean up after the build process. - -$(MAKE) distclean -ifneq "$(wildcard /usr/share/misc/config.sub)" "" - cp -f /usr/share/misc/config.sub config.sub -endif -ifneq "$(wildcard /usr/share/misc/config.guess)" "" - cp -f /usr/share/misc/config.guess config.guess -endif - - - dh_clean - -install: build - dh_testdir - dh_testroot - dh_clean -k - dh_installdirs - - # Add here commands to install the package into debian/tmp - $(MAKE) install DESTDIR=$(CURDIR)/debian/tmp - - -# Build architecture-independent files here. -binary-indep: build install -# We have nothing to do by default. - -# Build architecture-dependent files here. -binary-arch: build install - dh_testdir - dh_testroot - dh_installchangelogs ChangeLog - dh_installdocs - dh_installexamples - dh_install --sourcedir=debian/tmp -# dh_installmenu -# dh_installdebconf -# dh_installlogrotate -# dh_installemacsen -# dh_installpam -# dh_installmime -# dh_installinit -# dh_installcron -# dh_installinfo - dh_installman - dh_link - dh_strip - dh_compress - dh_fixperms -# dh_perl -# dh_python - dh_makeshlibs - dh_installdeb - dh_shlibdeps - dh_gencontrol - dh_md5sums - dh_builddeb - -binary: binary-indep binary-arch -.PHONY: build clean binary-indep binary-arch binary install diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/rpm.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/rpm.sh deleted file mode 100755 index e5649a22581..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/rpm.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/sh -e - -# Run this from the 'packages' directory, just under rootdir - -# We can only build rpm packages, if the rpm build tools are installed -if [ \! -x /usr/bin/rpmbuild ] -then - echo "Cannot find /usr/bin/rpmbuild. Not building an rpm." 1>&2 - exit 0 -fi - -# Check the commandline flags -PACKAGE="$1" -VERSION="$2" -fullname="${PACKAGE}-${VERSION}" -archive=../$fullname.tar.gz - -if [ -z "$1" -o -z "$2" ] -then - echo "Usage: $0 " 1>&2 - exit 0 -fi - -# Double-check we're in the packages directory, just under rootdir -if [ \! -r ../Makefile -a \! -r ../INSTALL ] -then - echo "Must run $0 in the 'packages' directory, under the root directory." 1>&2 - echo "Also, you must run \"make dist\" before running this script." 1>&2 - exit 0 -fi - -if [ \! -r "$archive" ] -then - echo "Cannot find $archive. Run \"make dist\" first." 1>&2 - exit 0 -fi - -# Create the directory where the input lives, and where the output should live -RPM_SOURCE_DIR="/tmp/rpmsource-$fullname" -RPM_BUILD_DIR="/tmp/rpmbuild-$fullname" - -trap 'rm -rf $RPM_SOURCE_DIR $RPM_BUILD_DIR; exit $?' EXIT SIGHUP SIGINT SIGTERM - -rm -rf "$RPM_SOURCE_DIR" "$RPM_BUILD_DIR" -mkdir "$RPM_SOURCE_DIR" -mkdir "$RPM_BUILD_DIR" - -cp "$archive" "$RPM_SOURCE_DIR"/v"$VERSION".tar.gz - -rpmbuild -bb rpm/rpm.spec \ - --define "NAME $PACKAGE" \ - --define "VERSION $VERSION" \ - --define "_sourcedir $RPM_SOURCE_DIR" \ - --define "_builddir $RPM_BUILD_DIR" \ - --define "_rpmdir $RPM_SOURCE_DIR" - -# We put the output in a directory based on what system we've built for -destdir=rpm-unknown -if [ -r /etc/issue ] -then - grep "Red Hat.*release 7" /etc/issue >/dev/null 2>&1 && destdir=rh7 - grep "Red Hat.*release 8" /etc/issue >/dev/null 2>&1 && destdir=rh8 - grep "Red Hat.*release 9" /etc/issue >/dev/null 2>&1 && destdir=rh9 - if grep Fedora /etc/issue >/dev/null; then - destdir=fc`grep Fedora /etc/issue | cut -d' ' -f 4`; - fi -fi - -rm -rf "$destdir" -mkdir -p "$destdir" -# We want to get not only the main package but devel etc, hence the middle * -mv "$RPM_SOURCE_DIR"/*/"${PACKAGE}"-*"${VERSION}"*.rpm "$destdir" - -echo -echo "The rpm package file(s) are located in $PWD/$destdir" diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/rpm/rpm.spec b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/rpm/rpm.spec deleted file mode 100644 index 24ef134df52..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/packages/rpm/rpm.spec +++ /dev/null @@ -1,72 +0,0 @@ -%define RELEASE 1 -%define rel %{?CUSTOM_RELEASE} %{!?CUSTOM_RELEASE:%RELEASE} -%define prefix /usr - -Name: %NAME -Summary: A C++ application logging library -Version: %VERSION -Release: %rel -Group: Development/Libraries -URL: http://github.com/google/glog -License: BSD -Vendor: Google -Packager: Google Inc. -Source: https://github.com/google/glog/archive/v%{VERSION}.tar.gz -Distribution: Redhat 7 and above. -Buildroot: %{_tmppath}/%{name}-root -Prefix: %prefix - -%description -The %name package contains a library that implements application-level -logging. This library provides logging APIs based on C++-style -streams and various helper macros. - -%package devel -Summary: A C++ application logging library -Group: Development/Libraries -Requires: %{NAME} = %{VERSION} - -%description devel -The %name-devel package contains static and debug libraries and header -files for developing applications that use the %name package. - -%changelog - * Wed Mar 26 2008 - - First draft - -%prep -%setup - -%build -./configure -make prefix=%prefix - -%install -rm -rf $RPM_BUILD_ROOT -make prefix=$RPM_BUILD_ROOT%{prefix} install - -%clean -rm -rf $RPM_BUILD_ROOT - -%files -%defattr(-,root,root) - -## Mark all installed files within /usr/share/doc/{package name} as -## documentation. This depends on the following two lines appearing in -## Makefile.am: -## docdir = $(prefix)/share/doc/$(PACKAGE)-$(VERSION) -## dist_doc_DATA = AUTHORS COPYING ChangeLog INSTALL README.md -%docdir %{prefix}/share/doc/%{NAME}-%{VERSION} -%{prefix}/share/doc/%{NAME}-%{VERSION}/* - -%{prefix}/lib/libglog.so.0 -%{prefix}/lib/libglog.so.0.0.0 - -%files devel -%defattr(-,root,root) - -%{prefix}/include/glog -%{prefix}/lib/libglog.a -%{prefix}/lib/libglog.la -%{prefix}/lib/libglog.so -%{prefix}/lib/pkgconfig/libglog.pc diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/base/commandlineflags.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/base/commandlineflags.h deleted file mode 100644 index c8d50890269..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/base/commandlineflags.h +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// --- -// This file is a compatibility layer that defines Google's version of -// command line flags that are used for configuration. -// -// We put flags into their own namespace. It is purposefully -// named in an opaque way that people should have trouble typing -// directly. The idea is that DEFINE puts the flag in the weird -// namespace, and DECLARE imports the flag from there into the -// current namespace. The net result is to force people to use -// DECLARE to get access to a flag, rather than saying -// extern bool FLAGS_logtostderr; -// or some such instead. We want this so we can put extra -// functionality (like sanity-checking) in DECLARE if we want, -// and make sure it is picked up everywhere. -// -// We also put the type of the variable in the namespace, so that -// people can't DECLARE_int32 something that they DEFINE_bool'd -// elsewhere. -#ifndef BASE_COMMANDLINEFLAGS_H__ -#define BASE_COMMANDLINEFLAGS_H__ - -#include "config.h" -#include -#include // for memchr -#include // for getenv - -#ifdef HAVE_LIB_GFLAGS - -#include - -#else - -#include "glog/logging.h" - -#define DECLARE_VARIABLE(type, shorttype, name, tn) \ - namespace fL##shorttype { \ - extern GOOGLE_GLOG_DLL_DECL type FLAGS_##name; \ - } \ - using fL##shorttype::FLAGS_##name -#define DEFINE_VARIABLE(type, shorttype, name, value, meaning, tn) \ - namespace fL##shorttype { \ - GOOGLE_GLOG_DLL_DECL type FLAGS_##name(value); \ - char FLAGS_no##name; \ - } \ - using fL##shorttype::FLAGS_##name - -// bool specialization -#define DECLARE_bool(name) \ - DECLARE_VARIABLE(bool, B, name, bool) -#define DEFINE_bool(name, value, meaning) \ - DEFINE_VARIABLE(bool, B, name, value, meaning, bool) - -// int32 specialization -#define DECLARE_int32(name) \ - DECLARE_VARIABLE(GOOGLE_NAMESPACE::int32, I, name, int32) -#define DEFINE_int32(name, value, meaning) \ - DEFINE_VARIABLE(GOOGLE_NAMESPACE::int32, I, name, value, meaning, int32) - -// Special case for string, because we have to specify the namespace -// std::string, which doesn't play nicely with our FLAG__namespace hackery. -#define DECLARE_string(name) \ - namespace fLS { \ - extern GOOGLE_GLOG_DLL_DECL std::string& FLAGS_##name; \ - } \ - using fLS::FLAGS_##name -#define DEFINE_string(name, value, meaning) \ - namespace fLS { \ - std::string FLAGS_##name##_buf(value); \ - GOOGLE_GLOG_DLL_DECL std::string& FLAGS_##name = FLAGS_##name##_buf; \ - char FLAGS_no##name; \ - } \ - using fLS::FLAGS_##name - -#endif // HAVE_LIB_GFLAGS - -// Define GLOG_DEFINE_* using DEFINE_* . By using these macros, we -// have GLOG_* environ variables even if we have gflags installed. -// -// If both an environment variable and a flag are specified, the value -// specified by a flag wins. E.g., if GLOG_v=0 and --v=1, the -// verbosity will be 1, not 0. - -#define GLOG_DEFINE_bool(name, value, meaning) \ - DEFINE_bool(name, EnvToBool("GLOG_" #name, value), meaning) - -#define GLOG_DEFINE_int32(name, value, meaning) \ - DEFINE_int32(name, EnvToInt("GLOG_" #name, value), meaning) - -#define GLOG_DEFINE_string(name, value, meaning) \ - DEFINE_string(name, EnvToString("GLOG_" #name, value), meaning) - -// These macros (could be functions, but I don't want to bother with a .cc -// file), make it easier to initialize flags from the environment. - -#define EnvToString(envname, dflt) \ - (!getenv(envname) ? (dflt) : getenv(envname)) - -#define EnvToBool(envname, dflt) \ - (!getenv(envname) ? (dflt) : memchr("tTyY1\0", getenv(envname)[0], 6) != NULL) - -#define EnvToInt(envname, dflt) \ - (!getenv(envname) ? (dflt) : strtol(getenv(envname), NULL, 10)) - -#endif // BASE_COMMANDLINEFLAGS_H__ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/base/googleinit.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/base/googleinit.h deleted file mode 100644 index 5a8b515cd60..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/base/googleinit.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// --- -// Author: Jacob Hoffman-Andrews - -#ifndef _GOOGLEINIT_H -#define _GOOGLEINIT_H - -class GoogleInitializer { - public: - typedef void (*void_function)(void); - GoogleInitializer(const char*, void_function f) { - f(); - } -}; - -#define REGISTER_MODULE_INITIALIZER(name, body) \ - namespace { \ - static void google_init_module_##name () { body; } \ - GoogleInitializer google_initializer_module_##name(#name, \ - google_init_module_##name); \ - } - -#endif /* _GOOGLEINIT_H */ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/base/mutex.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/base/mutex.h deleted file mode 100644 index ced2b9950ed..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/base/mutex.h +++ /dev/null @@ -1,333 +0,0 @@ -// Copyright (c) 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// --- -// Author: Craig Silverstein. -// -// A simple mutex wrapper, supporting locks and read-write locks. -// You should assume the locks are *not* re-entrant. -// -// To use: you should define the following macros in your configure.ac: -// ACX_PTHREAD -// AC_RWLOCK -// The latter is defined in ../autoconf. -// -// This class is meant to be internal-only and should be wrapped by an -// internal namespace. Before you use this module, please give the -// name of your internal namespace for this module. Or, if you want -// to expose it, you'll want to move it to the Google namespace. We -// cannot put this class in global namespace because there can be some -// problems when we have multiple versions of Mutex in each shared object. -// -// NOTE: by default, we have #ifdef'ed out the TryLock() method. -// This is for two reasons: -// 1) TryLock() under Windows is a bit annoying (it requires a -// #define to be defined very early). -// 2) TryLock() is broken for NO_THREADS mode, at least in NDEBUG -// mode. -// If you need TryLock(), and either these two caveats are not a -// problem for you, or you're willing to work around them, then -// feel free to #define GMUTEX_TRYLOCK, or to remove the #ifdefs -// in the code below. -// -// CYGWIN NOTE: Cygwin support for rwlock seems to be buggy: -// http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html -// Because of that, we might as well use windows locks for -// cygwin. They seem to be more reliable than the cygwin pthreads layer. -// -// TRICKY IMPLEMENTATION NOTE: -// This class is designed to be safe to use during -// dynamic-initialization -- that is, by global constructors that are -// run before main() starts. The issue in this case is that -// dynamic-initialization happens in an unpredictable order, and it -// could be that someone else's dynamic initializer could call a -// function that tries to acquire this mutex -- but that all happens -// before this mutex's constructor has run. (This can happen even if -// the mutex and the function that uses the mutex are in the same .cc -// file.) Basically, because Mutex does non-trivial work in its -// constructor, it's not, in the naive implementation, safe to use -// before dynamic initialization has run on it. -// -// The solution used here is to pair the actual mutex primitive with a -// bool that is set to true when the mutex is dynamically initialized. -// (Before that it's false.) Then we modify all mutex routines to -// look at the bool, and not try to lock/unlock until the bool makes -// it to true (which happens after the Mutex constructor has run.) -// -// This works because before main() starts -- particularly, during -// dynamic initialization -- there are no threads, so a) it's ok that -// the mutex operations are a no-op, since we don't need locking then -// anyway; and b) we can be quite confident our bool won't change -// state between a call to Lock() and a call to Unlock() (that would -// require a global constructor in one translation unit to call Lock() -// and another global constructor in another translation unit to call -// Unlock() later, which is pretty perverse). -// -// That said, it's tricky, and can conceivably fail; it's safest to -// avoid trying to acquire a mutex in a global constructor, if you -// can. One way it can fail is that a really smart compiler might -// initialize the bool to true at static-initialization time (too -// early) rather than at dynamic-initialization time. To discourage -// that, we set is_safe_ to true in code (not the constructor -// colon-initializer) and set it to true via a function that always -// evaluates to true, but that the compiler can't know always -// evaluates to true. This should be good enough. - -#ifndef GOOGLE_MUTEX_H_ -#define GOOGLE_MUTEX_H_ - -#include "config.h" // to figure out pthreads support - -#if defined(NO_THREADS) - typedef int MutexType; // to keep a lock-count -#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__) -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN // We only need minimal includes -# endif -# ifdef GMUTEX_TRYLOCK - // We need Windows NT or later for TryEnterCriticalSection(). If you - // don't need that functionality, you can remove these _WIN32_WINNT - // lines, and change TryLock() to assert(0) or something. -# ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0400 -# endif -# endif -// To avoid macro definition of ERROR. -# ifndef NOGDI -# define NOGDI -# endif -// To avoid macro definition of min/max. -# ifndef NOMINMAX -# define NOMINMAX -# endif -# include - typedef CRITICAL_SECTION MutexType; -#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) - // Needed for pthread_rwlock_*. If it causes problems, you could take it - // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it - // *does* cause problems for FreeBSD, or MacOSX, but isn't needed - // for locking there.) -# ifdef __linux__ -# ifndef _XOPEN_SOURCE // Some other header might have already set it for us. -# define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls -# endif -# endif -# include - typedef pthread_rwlock_t MutexType; -#elif defined(HAVE_PTHREAD) -# include - typedef pthread_mutex_t MutexType; -#else -# error Need to implement mutex.h for your architecture, or #define NO_THREADS -#endif - -// We need to include these header files after defining _XOPEN_SOURCE -// as they may define the _XOPEN_SOURCE macro. -#include -#include // for abort() - -#define MUTEX_NAMESPACE glog_internal_namespace_ - -namespace MUTEX_NAMESPACE { - -class Mutex { - public: - // Create a Mutex that is not held by anybody. This constructor is - // typically used for Mutexes allocated on the heap or the stack. - // See below for a recommendation for constructing global Mutex - // objects. - inline Mutex(); - - // Destructor - inline ~Mutex(); - - inline void Lock(); // Block if needed until free then acquire exclusively - inline void Unlock(); // Release a lock acquired via Lock() -#ifdef GMUTEX_TRYLOCK - inline bool TryLock(); // If free, Lock() and return true, else return false -#endif - // Note that on systems that don't support read-write locks, these may - // be implemented as synonyms to Lock() and Unlock(). So you can use - // these for efficiency, but don't use them anyplace where being able - // to do shared reads is necessary to avoid deadlock. - inline void ReaderLock(); // Block until free or shared then acquire a share - inline void ReaderUnlock(); // Release a read share of this Mutex - inline void WriterLock() { Lock(); } // Acquire an exclusive lock - inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock() - - // TODO(hamaji): Do nothing, implement correctly. - inline void AssertHeld() {} - - private: - MutexType mutex_; - // We want to make sure that the compiler sets is_safe_ to true only - // when we tell it to, and never makes assumptions is_safe_ is - // always true. volatile is the most reliable way to do that. - volatile bool is_safe_; - - inline void SetIsSafe() { is_safe_ = true; } - - // Catch the error of writing Mutex when intending MutexLock. - Mutex(Mutex* /*ignored*/) {} - // Disallow "evil" constructors - Mutex(const Mutex&); - void operator=(const Mutex&); -}; - -// Now the implementation of Mutex for various systems -#if defined(NO_THREADS) - -// When we don't have threads, we can be either reading or writing, -// but not both. We can have lots of readers at once (in no-threads -// mode, that's most likely to happen in recursive function calls), -// but only one writer. We represent this by having mutex_ be -1 when -// writing and a number > 0 when reading (and 0 when no lock is held). -// -// In debug mode, we assert these invariants, while in non-debug mode -// we do nothing, for efficiency. That's why everything is in an -// assert. - -Mutex::Mutex() : mutex_(0) { } -Mutex::~Mutex() { assert(mutex_ == 0); } -void Mutex::Lock() { assert(--mutex_ == -1); } -void Mutex::Unlock() { assert(mutex_++ == -1); } -#ifdef GMUTEX_TRYLOCK -bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; } -#endif -void Mutex::ReaderLock() { assert(++mutex_ > 0); } -void Mutex::ReaderUnlock() { assert(mutex_-- > 0); } - -#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__) - -Mutex::Mutex() { InitializeCriticalSection(&mutex_); SetIsSafe(); } -Mutex::~Mutex() { DeleteCriticalSection(&mutex_); } -void Mutex::Lock() { if (is_safe_) EnterCriticalSection(&mutex_); } -void Mutex::Unlock() { if (is_safe_) LeaveCriticalSection(&mutex_); } -#ifdef GMUTEX_TRYLOCK -bool Mutex::TryLock() { return is_safe_ ? - TryEnterCriticalSection(&mutex_) != 0 : true; } -#endif -void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks -void Mutex::ReaderUnlock() { Unlock(); } - -#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) - -#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ - if (is_safe_ && fncall(&mutex_) != 0) abort(); \ -} while (0) - -Mutex::Mutex() { - SetIsSafe(); - if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); -} -Mutex::~Mutex() { SAFE_PTHREAD(pthread_rwlock_destroy); } -void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); } -void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } -#ifdef GMUTEX_TRYLOCK -bool Mutex::TryLock() { return is_safe_ ? - pthread_rwlock_trywrlock(&mutex_) == 0 : - true; } -#endif -void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); } -void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } -#undef SAFE_PTHREAD - -#elif defined(HAVE_PTHREAD) - -#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ - if (is_safe_ && fncall(&mutex_) != 0) abort(); \ -} while (0) - -Mutex::Mutex() { - SetIsSafe(); - if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort(); -} -Mutex::~Mutex() { SAFE_PTHREAD(pthread_mutex_destroy); } -void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); } -void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); } -#ifdef GMUTEX_TRYLOCK -bool Mutex::TryLock() { return is_safe_ ? - pthread_mutex_trylock(&mutex_) == 0 : true; } -#endif -void Mutex::ReaderLock() { Lock(); } -void Mutex::ReaderUnlock() { Unlock(); } -#undef SAFE_PTHREAD - -#endif - -// -------------------------------------------------------------------------- -// Some helper classes - -// MutexLock(mu) acquires mu when constructed and releases it when destroyed. -class MutexLock { - public: - explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); } - ~MutexLock() { mu_->Unlock(); } - private: - Mutex * const mu_; - // Disallow "evil" constructors - MutexLock(const MutexLock&); - void operator=(const MutexLock&); -}; - -// ReaderMutexLock and WriterMutexLock do the same, for rwlocks -class ReaderMutexLock { - public: - explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); } - ~ReaderMutexLock() { mu_->ReaderUnlock(); } - private: - Mutex * const mu_; - // Disallow "evil" constructors - ReaderMutexLock(const ReaderMutexLock&); - void operator=(const ReaderMutexLock&); -}; - -class WriterMutexLock { - public: - explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); } - ~WriterMutexLock() { mu_->WriterUnlock(); } - private: - Mutex * const mu_; - // Disallow "evil" constructors - WriterMutexLock(const WriterMutexLock&); - void operator=(const WriterMutexLock&); -}; - -// Catch bug where variable name is omitted, e.g. MutexLock (&mu); -#define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name) -#define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name) -#define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name) - -} // namespace MUTEX_NAMESPACE - -using namespace MUTEX_NAMESPACE; - -#undef MUTEX_NAMESPACE - -#endif /* #define GOOGLE_MUTEX_H__ */ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/config.h.cmake.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/config.h.cmake.in deleted file mode 100644 index ee8cdfe2275..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/config.h.cmake.in +++ /dev/null @@ -1,216 +0,0 @@ -#ifndef GLOG_CONFIG_H -#define GLOG_CONFIG_H - -/* define if glog doesn't use RTTI */ -#cmakedefine DISABLE_RTTI - -/* Namespace for Google classes */ -#cmakedefine GOOGLE_NAMESPACE ${GOOGLE_NAMESPACE} - -/* Define if you have the `dladdr' function */ -#cmakedefine HAVE_DLADDR - -/* Define if you have the `snprintf' function */ -#cmakedefine HAVE_SNPRINTF - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_DLFCN_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_EXECINFO_H - -/* Define if you have the `fcntl' function */ -#cmakedefine HAVE_FCNTL - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_GLOB_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_INTTYPES_H ${HAVE_INTTYPES_H} - -/* Define to 1 if you have the `pthread' library (-lpthread). */ -#cmakedefine HAVE_LIBPTHREAD - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_LIBUNWIND_H - -/* define if you have google gflags library */ -#cmakedefine HAVE_LIB_GFLAGS - -/* define if you have google gmock library */ -#cmakedefine HAVE_LIB_GMOCK - -/* define if you have google gtest library */ -#cmakedefine HAVE_LIB_GTEST - -/* define if you have libunwind */ -#cmakedefine HAVE_LIB_UNWIND - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_MEMORY_H - -/* define to disable multithreading support. */ -#cmakedefine NO_THREADS - -/* define if the compiler implements namespaces */ -#cmakedefine HAVE_NAMESPACES - -/* Define if you have the 'pread' function */ -#cmakedefine HAVE_PREAD - -/* Define if you have POSIX threads libraries and header files. */ -#cmakedefine HAVE_PTHREAD - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_PWD_H - -/* Define if you have the 'pwrite' function */ -#cmakedefine HAVE_PWRITE - -/* define if the compiler implements pthread_rwlock_* */ -#cmakedefine HAVE_RWLOCK - -/* Define if you have the 'sigaction' function */ -#cmakedefine HAVE_SIGACTION - -/* Define if you have the `sigaltstack' function */ -#cmakedefine HAVE_SIGALTSTACK - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_STDINT_H ${HAVE_STDINT_H} - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_STDLIB_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_STRINGS_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_STRING_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYSCALL_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYSLOG_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_STAT_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_SYSCALL_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_TIME_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_TYPES_H ${HAVE_SYS_TYPES_H} - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_UCONTEXT_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_UTSNAME_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_UCONTEXT_H - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_UNISTD_H ${HAVE_UNISTD_H} - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_UNWIND_H ${HAVE_UNWIND_H} - -/* define if the compiler supports using expression for operator */ -#cmakedefine HAVE_USING_OPERATOR - -/* define if your compiler has __attribute__ */ -#cmakedefine HAVE___ATTRIBUTE__ - -/* define if your compiler has __builtin_expect */ -#cmakedefine HAVE___BUILTIN_EXPECT ${HAVE___BUILTIN_EXPECT} - -/* define if your compiler has __sync_val_compare_and_swap */ -#cmakedefine HAVE___SYNC_VAL_COMPARE_AND_SWAP - -/* define if symbolize support is available */ -#cmakedefine HAVE_SYMBOLIZE - -/* define if localtime_r is available in time.h */ -#cmakedefine HAVE_LOCALTIME_R - -/* Define to the sub-directory in which libtool stores uninstalled libraries. - */ -#cmakedefine LT_OBJDIR - -/* Name of package */ -#cmakedefine PACKAGE - -/* Define to the address where bug reports for this package should be sent. */ -#cmakedefine PACKAGE_BUGREPORT - -/* Define to the full name of this package. */ -#cmakedefine PACKAGE_NAME - -/* Define to the full name and version of this package. */ -#cmakedefine PACKAGE_STRING - -/* Define to the one symbol short name of this package. */ -#cmakedefine PACKAGE_TARNAME - -/* Define to the home page for this package. */ -#cmakedefine PACKAGE_URL - -/* Define to the version of this package. */ -#cmakedefine PACKAGE_VERSION - -/* How to access the PC from a struct ucontext */ -#cmakedefine PC_FROM_UCONTEXT - -/* define if we should print raw pc values on symbolization failure. */ -#cmakedefine PRINT_UNSYMBOLIZED_STACK_TRACES - -/* Define to necessary symbol if this constant uses a non-standard name on - your system. */ -#cmakedefine PTHREAD_CREATE_JOINABLE - -/* The size of `void *', as computed by sizeof. */ -#cmakedefine SIZEOF_VOID_P ${SIZEOF_VOID_P} - -/* Define to 1 if you have the ANSI C header files. */ -#cmakedefine STDC_HEADERS - -/* the namespace where STL code like vector<> is defined */ -#cmakedefine STL_NAMESPACE ${STL_NAMESPACE} - -/* location of source code */ -#cmakedefine TEST_SRC_DIR ${TEST_SRC_DIR} - -/* Define to necessary thread-local storage attribute. */ -#cmakedefine GLOG_THREAD_LOCAL_STORAGE ${GLOG_THREAD_LOCAL_STORAGE} - -/* Check whether aligned_storage and alignof present */ -#cmakedefine HAVE_ALIGNED_STORAGE ${HAVE_ALIGNED_STORAGE} - -/* Version number of package */ -#cmakedefine VERSION - -#ifdef GLOG_BAZEL_BUILD - -/* TODO(rodrigoq): remove this workaround once bazel#3979 is resolved: - * https://github.com/bazelbuild/bazel/issues/3979 */ -#define _START_GOOGLE_NAMESPACE_ namespace GOOGLE_NAMESPACE { - -#define _END_GOOGLE_NAMESPACE_ } - -#else - -/* Stops putting the code inside the Google namespace */ -#cmakedefine _END_GOOGLE_NAMESPACE_ ${_END_GOOGLE_NAMESPACE_} - -/* Puts following code inside the Google namespace */ -#cmakedefine _START_GOOGLE_NAMESPACE_ ${_START_GOOGLE_NAMESPACE_} - -#endif - -#endif // GLOG_CONFIG_H diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/config_for_unittests.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/config_for_unittests.h deleted file mode 100644 index 13ea8eab7a3..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/config_for_unittests.h +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// --- -// All Rights Reserved. -// -// Author: Craig Silverstein -// Copied from google-perftools and modified by Shinichiro Hamaji -// -// This file is needed for windows -- unittests are not part of the -// glog dll, but still want to include config.h just like the -// dll does, so they can use internal tools and APIs for testing. -// -// The problem is that config.h declares GOOGLE_GLOG_DLL_DECL to be -// for exporting symbols, but the unittest needs to *import* symbols -// (since it's not the dll). -// -// The solution is to have this file, which is just like config.h but -// sets GOOGLE_GLOG_DLL_DECL to do a dllimport instead of a dllexport. -// -// The reason we need this extra GOOGLE_GLOG_DLL_DECL_FOR_UNITTESTS -// variable is in case people want to set GOOGLE_GLOG_DLL_DECL explicitly -// to something other than __declspec(dllexport). In that case, they -// may want to use something other than __declspec(dllimport) for the -// unittest case. For that, we allow folks to define both -// GOOGLE_GLOG_DLL_DECL and GOOGLE_GLOG_DLL_DECL_FOR_UNITTESTS explicitly. -// -// NOTE: This file is equivalent to config.h on non-windows systems, -// which never defined GOOGLE_GLOG_DLL_DECL_FOR_UNITTESTS and always -// define GOOGLE_GLOG_DLL_DECL to the empty string. - -#include "config.h" - -#undef GOOGLE_GLOG_DLL_DECL -#ifdef GOOGLE_GLOG_DLL_DECL_FOR_UNITTESTS -# define GOOGLE_GLOG_DLL_DECL GOOGLE_GLOG_DLL_DECL_FOR_UNITTESTS -#else -// if DLL_DECL_FOR_UNITTESTS isn't defined, use "" -# define GOOGLE_GLOG_DLL_DECL -#endif diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle.cc deleted file mode 100644 index 9369f9a65c2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle.cc +++ /dev/null @@ -1,1356 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Satoru Takabayashi -// -// For reference check out: -// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling -// -// Note that we only have partial C++0x support yet. - -#include // for NULL -#include "utilities.h" -#include "demangle.h" - -#if defined(OS_WINDOWS) -#include -#pragma comment(lib, "dbghelp") -#endif - -_START_GOOGLE_NAMESPACE_ - -#if !defined(OS_WINDOWS) -typedef struct { - const char *abbrev; - const char *real_name; -} AbbrevPair; - -// List of operators from Itanium C++ ABI. -static const AbbrevPair kOperatorList[] = { - { "nw", "new" }, - { "na", "new[]" }, - { "dl", "delete" }, - { "da", "delete[]" }, - { "ps", "+" }, - { "ng", "-" }, - { "ad", "&" }, - { "de", "*" }, - { "co", "~" }, - { "pl", "+" }, - { "mi", "-" }, - { "ml", "*" }, - { "dv", "/" }, - { "rm", "%" }, - { "an", "&" }, - { "or", "|" }, - { "eo", "^" }, - { "aS", "=" }, - { "pL", "+=" }, - { "mI", "-=" }, - { "mL", "*=" }, - { "dV", "/=" }, - { "rM", "%=" }, - { "aN", "&=" }, - { "oR", "|=" }, - { "eO", "^=" }, - { "ls", "<<" }, - { "rs", ">>" }, - { "lS", "<<=" }, - { "rS", ">>=" }, - { "eq", "==" }, - { "ne", "!=" }, - { "lt", "<" }, - { "gt", ">" }, - { "le", "<=" }, - { "ge", ">=" }, - { "nt", "!" }, - { "aa", "&&" }, - { "oo", "||" }, - { "pp", "++" }, - { "mm", "--" }, - { "cm", "," }, - { "pm", "->*" }, - { "pt", "->" }, - { "cl", "()" }, - { "ix", "[]" }, - { "qu", "?" }, - { "st", "sizeof" }, - { "sz", "sizeof" }, - { NULL, NULL }, -}; - -// List of builtin types from Itanium C++ ABI. -static const AbbrevPair kBuiltinTypeList[] = { - { "v", "void" }, - { "w", "wchar_t" }, - { "b", "bool" }, - { "c", "char" }, - { "a", "signed char" }, - { "h", "unsigned char" }, - { "s", "short" }, - { "t", "unsigned short" }, - { "i", "int" }, - { "j", "unsigned int" }, - { "l", "long" }, - { "m", "unsigned long" }, - { "x", "long long" }, - { "y", "unsigned long long" }, - { "n", "__int128" }, - { "o", "unsigned __int128" }, - { "f", "float" }, - { "d", "double" }, - { "e", "long double" }, - { "g", "__float128" }, - { "z", "ellipsis" }, - { NULL, NULL } -}; - -// List of substitutions Itanium C++ ABI. -static const AbbrevPair kSubstitutionList[] = { - { "St", "" }, - { "Sa", "allocator" }, - { "Sb", "basic_string" }, - // std::basic_string,std::allocator > - { "Ss", "string"}, - // std::basic_istream > - { "Si", "istream" }, - // std::basic_ostream > - { "So", "ostream" }, - // std::basic_iostream > - { "Sd", "iostream" }, - { NULL, NULL } -}; - -// State needed for demangling. -typedef struct { - const char *mangled_cur; // Cursor of mangled name. - char *out_cur; // Cursor of output string. - const char *out_begin; // Beginning of output string. - const char *out_end; // End of output string. - const char *prev_name; // For constructors/destructors. - int prev_name_length; // For constructors/destructors. - short nest_level; // For nested names. - bool append; // Append flag. - bool overflowed; // True if output gets overflowed. -} State; - -// We don't use strlen() in libc since it's not guaranteed to be async -// signal safe. -static size_t StrLen(const char *str) { - size_t len = 0; - while (*str != '\0') { - ++str; - ++len; - } - return len; -} - -// Returns true if "str" has at least "n" characters remaining. -static bool AtLeastNumCharsRemaining(const char *str, int n) { - for (int i = 0; i < n; ++i) { - if (str[i] == '\0') { - return false; - } - } - return true; -} - -// Returns true if "str" has "prefix" as a prefix. -static bool StrPrefix(const char *str, const char *prefix) { - size_t i = 0; - while (str[i] != '\0' && prefix[i] != '\0' && - str[i] == prefix[i]) { - ++i; - } - return prefix[i] == '\0'; // Consumed everything in "prefix". -} - -static void InitState(State *state, const char *mangled, - char *out, int out_size) { - state->mangled_cur = mangled; - state->out_cur = out; - state->out_begin = out; - state->out_end = out + out_size; - state->prev_name = NULL; - state->prev_name_length = -1; - state->nest_level = -1; - state->append = true; - state->overflowed = false; -} - -// Returns true and advances "mangled_cur" if we find "one_char_token" -// at "mangled_cur" position. It is assumed that "one_char_token" does -// not contain '\0'. -static bool ParseOneCharToken(State *state, const char one_char_token) { - if (state->mangled_cur[0] == one_char_token) { - ++state->mangled_cur; - return true; - } - return false; -} - -// Returns true and advances "mangled_cur" if we find "two_char_token" -// at "mangled_cur" position. It is assumed that "two_char_token" does -// not contain '\0'. -static bool ParseTwoCharToken(State *state, const char *two_char_token) { - if (state->mangled_cur[0] == two_char_token[0] && - state->mangled_cur[1] == two_char_token[1]) { - state->mangled_cur += 2; - return true; - } - return false; -} - -// Returns true and advances "mangled_cur" if we find any character in -// "char_class" at "mangled_cur" position. -static bool ParseCharClass(State *state, const char *char_class) { - const char *p = char_class; - for (; *p != '\0'; ++p) { - if (state->mangled_cur[0] == *p) { - ++state->mangled_cur; - return true; - } - } - return false; -} - -// This function is used for handling an optional non-terminal. -static bool Optional(bool) { - return true; -} - -// This function is used for handling + syntax. -typedef bool (*ParseFunc)(State *); -static bool OneOrMore(ParseFunc parse_func, State *state) { - if (parse_func(state)) { - while (parse_func(state)) { - } - return true; - } - return false; -} - -// This function is used for handling * syntax. The function -// always returns true and must be followed by a termination token or a -// terminating sequence not handled by parse_func (e.g. -// ParseOneCharToken(state, 'E')). -static bool ZeroOrMore(ParseFunc parse_func, State *state) { - while (parse_func(state)) { - } - return true; -} - -// Append "str" at "out_cur". If there is an overflow, "overflowed" -// is set to true for later use. The output string is ensured to -// always terminate with '\0' as long as there is no overflow. -static void Append(State *state, const char * const str, const int length) { - int i; - for (i = 0; i < length; ++i) { - if (state->out_cur + 1 < state->out_end) { // +1 for '\0' - *state->out_cur = str[i]; - ++state->out_cur; - } else { - state->overflowed = true; - break; - } - } - if (!state->overflowed) { - *state->out_cur = '\0'; // Terminate it with '\0' - } -} - -// We don't use equivalents in libc to avoid locale issues. -static bool IsLower(char c) { - return c >= 'a' && c <= 'z'; -} - -static bool IsAlpha(char c) { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); -} - -static bool IsDigit(char c) { - return c >= '0' && c <= '9'; -} - -// Returns true if "str" is a function clone suffix. These suffixes are used -// by GCC 4.5.x and later versions to indicate functions which have been -// cloned during optimization. We treat any sequence (.+.+)+ as -// a function clone suffix. -static bool IsFunctionCloneSuffix(const char *str) { - size_t i = 0; - while (str[i] != '\0') { - // Consume a single .+.+ sequence. - if (str[i] != '.' || !IsAlpha(str[i + 1])) { - return false; - } - i += 2; - while (IsAlpha(str[i])) { - ++i; - } - if (str[i] != '.' || !IsDigit(str[i + 1])) { - return false; - } - i += 2; - while (IsDigit(str[i])) { - ++i; - } - } - return true; // Consumed everything in "str". -} - -// Append "str" with some tweaks, iff "append" state is true. -// Returns true so that it can be placed in "if" conditions. -static void MaybeAppendWithLength(State *state, const char * const str, - const int length) { - if (state->append && length > 0) { - // Append a space if the output buffer ends with '<' and "str" - // starts with '<' to avoid <<<. - if (str[0] == '<' && state->out_begin < state->out_cur && - state->out_cur[-1] == '<') { - Append(state, " ", 1); - } - // Remember the last identifier name for ctors/dtors. - if (IsAlpha(str[0]) || str[0] == '_') { - state->prev_name = state->out_cur; - state->prev_name_length = length; - } - Append(state, str, length); - } -} - -// A convenient wrapper arount MaybeAppendWithLength(). -static bool MaybeAppend(State *state, const char * const str) { - if (state->append) { - int length = StrLen(str); - MaybeAppendWithLength(state, str, length); - } - return true; -} - -// This function is used for handling nested names. -static bool EnterNestedName(State *state) { - state->nest_level = 0; - return true; -} - -// This function is used for handling nested names. -static bool LeaveNestedName(State *state, short prev_value) { - state->nest_level = prev_value; - return true; -} - -// Disable the append mode not to print function parameters, etc. -static bool DisableAppend(State *state) { - state->append = false; - return true; -} - -// Restore the append mode to the previous state. -static bool RestoreAppend(State *state, bool prev_value) { - state->append = prev_value; - return true; -} - -// Increase the nest level for nested names. -static void MaybeIncreaseNestLevel(State *state) { - if (state->nest_level > -1) { - ++state->nest_level; - } -} - -// Appends :: for nested names if necessary. -static void MaybeAppendSeparator(State *state) { - if (state->nest_level >= 1) { - MaybeAppend(state, "::"); - } -} - -// Cancel the last separator if necessary. -static void MaybeCancelLastSeparator(State *state) { - if (state->nest_level >= 1 && state->append && - state->out_begin <= state->out_cur - 2) { - state->out_cur -= 2; - *state->out_cur = '\0'; - } -} - -// Returns true if the identifier of the given length pointed to by -// "mangled_cur" is anonymous namespace. -static bool IdentifierIsAnonymousNamespace(State *state, int length) { - static const char anon_prefix[] = "_GLOBAL__N_"; - return (length > (int)sizeof(anon_prefix) - 1 && // Should be longer. - StrPrefix(state->mangled_cur, anon_prefix)); -} - -// Forward declarations of our parsing functions. -static bool ParseMangledName(State *state); -static bool ParseEncoding(State *state); -static bool ParseName(State *state); -static bool ParseUnscopedName(State *state); -static bool ParseUnscopedTemplateName(State *state); -static bool ParseNestedName(State *state); -static bool ParsePrefix(State *state); -static bool ParseUnqualifiedName(State *state); -static bool ParseSourceName(State *state); -static bool ParseLocalSourceName(State *state); -static bool ParseNumber(State *state, int *number_out); -static bool ParseFloatNumber(State *state); -static bool ParseSeqId(State *state); -static bool ParseIdentifier(State *state, int length); -static bool ParseAbiTags(State *state); -static bool ParseAbiTag(State *state); -static bool ParseOperatorName(State *state); -static bool ParseSpecialName(State *state); -static bool ParseCallOffset(State *state); -static bool ParseNVOffset(State *state); -static bool ParseVOffset(State *state); -static bool ParseCtorDtorName(State *state); -static bool ParseType(State *state); -static bool ParseCVQualifiers(State *state); -static bool ParseBuiltinType(State *state); -static bool ParseFunctionType(State *state); -static bool ParseBareFunctionType(State *state); -static bool ParseClassEnumType(State *state); -static bool ParseArrayType(State *state); -static bool ParsePointerToMemberType(State *state); -static bool ParseTemplateParam(State *state); -static bool ParseTemplateTemplateParam(State *state); -static bool ParseTemplateArgs(State *state); -static bool ParseTemplateArg(State *state); -static bool ParseExpression(State *state); -static bool ParseExprPrimary(State *state); -static bool ParseLocalName(State *state); -static bool ParseDiscriminator(State *state); -static bool ParseSubstitution(State *state); - -// Implementation note: the following code is a straightforward -// translation of the Itanium C++ ABI defined in BNF with a couple of -// exceptions. -// -// - Support GNU extensions not defined in the Itanium C++ ABI -// - and are combined to avoid infinite loop -// - Reorder patterns to shorten the code -// - Reorder patterns to give greedier functions precedence -// We'll mark "Less greedy than" for these cases in the code -// -// Each parsing function changes the state and returns true on -// success. Otherwise, don't change the state and returns false. To -// ensure that the state isn't changed in the latter case, we save the -// original state before we call more than one parsing functions -// consecutively with &&, and restore the state if unsuccessful. See -// ParseEncoding() as an example of this convention. We follow the -// convention throughout the code. -// -// Originally we tried to do demangling without following the full ABI -// syntax but it turned out we needed to follow the full syntax to -// parse complicated cases like nested template arguments. Note that -// implementing a full-fledged demangler isn't trivial (libiberty's -// cp-demangle.c has +4300 lines). -// -// Note that (foo) in <(foo) ...> is a modifier to be ignored. -// -// Reference: -// - Itanium C++ ABI -// - -// ::= _Z -static bool ParseMangledName(State *state) { - return ParseTwoCharToken(state, "_Z") && ParseEncoding(state); -} - -// ::= <(function) name> -// ::= <(data) name> -// ::= -static bool ParseEncoding(State *state) { - State copy = *state; - if (ParseName(state) && ParseBareFunctionType(state)) { - return true; - } - *state = copy; - - if (ParseName(state) || ParseSpecialName(state)) { - return true; - } - return false; -} - -// ::= -// ::= -// ::= -// ::= -static bool ParseName(State *state) { - if (ParseNestedName(state) || ParseLocalName(state)) { - return true; - } - - State copy = *state; - if (ParseUnscopedTemplateName(state) && - ParseTemplateArgs(state)) { - return true; - } - *state = copy; - - // Less greedy than . - if (ParseUnscopedName(state)) { - return true; - } - return false; -} - -// ::= -// ::= St -static bool ParseUnscopedName(State *state) { - if (ParseUnqualifiedName(state)) { - return true; - } - - State copy = *state; - if (ParseTwoCharToken(state, "St") && - MaybeAppend(state, "std::") && - ParseUnqualifiedName(state)) { - return true; - } - *state = copy; - return false; -} - -// ::= -// ::= -static bool ParseUnscopedTemplateName(State *state) { - return ParseUnscopedName(state) || ParseSubstitution(state); -} - -// ::= N [] E -// ::= N [] E -static bool ParseNestedName(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'N') && - EnterNestedName(state) && - Optional(ParseCVQualifiers(state)) && - ParsePrefix(state) && - LeaveNestedName(state, copy.nest_level) && - ParseOneCharToken(state, 'E')) { - return true; - } - *state = copy; - return false; -} - -// This part is tricky. If we literally translate them to code, we'll -// end up infinite loop. Hence we merge them to avoid the case. -// -// ::= -// ::= -// ::= -// ::= -// ::= # empty -// ::= <(template) unqualified-name> -// ::= -// ::= -static bool ParsePrefix(State *state) { - bool has_something = false; - while (true) { - MaybeAppendSeparator(state); - if (ParseTemplateParam(state) || - ParseSubstitution(state) || - ParseUnscopedName(state)) { - has_something = true; - MaybeIncreaseNestLevel(state); - continue; - } - MaybeCancelLastSeparator(state); - if (has_something && ParseTemplateArgs(state)) { - return ParsePrefix(state); - } else { - break; - } - } - return true; -} - -// ::= -// ::= -// ::= [] -// ::= [] -static bool ParseUnqualifiedName(State *state) { - return (ParseOperatorName(state) || - ParseCtorDtorName(state) || - (ParseSourceName(state) && Optional(ParseAbiTags(state))) || - (ParseLocalSourceName(state) && Optional(ParseAbiTags(state)))); -} - -// ::= -static bool ParseSourceName(State *state) { - State copy = *state; - int length = -1; - if (ParseNumber(state, &length) && ParseIdentifier(state, length)) { - return true; - } - *state = copy; - return false; -} - -// ::= L [] -// -// References: -// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775 -// http://gcc.gnu.org/viewcvs?view=rev&revision=124467 -static bool ParseLocalSourceName(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'L') && ParseSourceName(state) && - Optional(ParseDiscriminator(state))) { - return true; - } - *state = copy; - return false; -} - -// ::= [n] -// If "number_out" is non-null, then *number_out is set to the value of the -// parsed number on success. -static bool ParseNumber(State *state, int *number_out) { - int sign = 1; - if (ParseOneCharToken(state, 'n')) { - sign = -1; - } - const char *p = state->mangled_cur; - int number = 0; - for (;*p != '\0'; ++p) { - if (IsDigit(*p)) { - number = number * 10 + (*p - '0'); - } else { - break; - } - } - if (p != state->mangled_cur) { // Conversion succeeded. - state->mangled_cur = p; - if (number_out != NULL) { - *number_out = number * sign; - } - return true; - } - return false; -} - -// Floating-point literals are encoded using a fixed-length lowercase -// hexadecimal string. -static bool ParseFloatNumber(State *state) { - const char *p = state->mangled_cur; - for (;*p != '\0'; ++p) { - if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) { - break; - } - } - if (p != state->mangled_cur) { // Conversion succeeded. - state->mangled_cur = p; - return true; - } - return false; -} - -// The is a sequence number in base 36, -// using digits and upper case letters -static bool ParseSeqId(State *state) { - const char *p = state->mangled_cur; - for (;*p != '\0'; ++p) { - if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) { - break; - } - } - if (p != state->mangled_cur) { // Conversion succeeded. - state->mangled_cur = p; - return true; - } - return false; -} - -// ::= (of given length) -static bool ParseIdentifier(State *state, int length) { - if (length == -1 || - !AtLeastNumCharsRemaining(state->mangled_cur, length)) { - return false; - } - if (IdentifierIsAnonymousNamespace(state, length)) { - MaybeAppend(state, "(anonymous namespace)"); - } else { - MaybeAppendWithLength(state, state->mangled_cur, length); - } - state->mangled_cur += length; - return true; -} - -// ::= [] -static bool ParseAbiTags(State *state) { - State copy = *state; - DisableAppend(state); - if (OneOrMore(ParseAbiTag, state)) { - RestoreAppend(state, copy.append); - return true; - } - *state = copy; - return false; -} - -// ::= B -static bool ParseAbiTag(State *state) { - return ParseOneCharToken(state, 'B') && ParseSourceName(state); -} - -// ::= nw, and other two letters cases -// ::= cv # (cast) -// ::= v # vendor extended operator -static bool ParseOperatorName(State *state) { - if (!AtLeastNumCharsRemaining(state->mangled_cur, 2)) { - return false; - } - // First check with "cv" (cast) case. - State copy = *state; - if (ParseTwoCharToken(state, "cv") && - MaybeAppend(state, "operator ") && - EnterNestedName(state) && - ParseType(state) && - LeaveNestedName(state, copy.nest_level)) { - return true; - } - *state = copy; - - // Then vendor extended operators. - if (ParseOneCharToken(state, 'v') && ParseCharClass(state, "0123456789") && - ParseSourceName(state)) { - return true; - } - *state = copy; - - // Other operator names should start with a lower alphabet followed - // by a lower/upper alphabet. - if (!(IsLower(state->mangled_cur[0]) && - IsAlpha(state->mangled_cur[1]))) { - return false; - } - // We may want to perform a binary search if we really need speed. - const AbbrevPair *p; - for (p = kOperatorList; p->abbrev != NULL; ++p) { - if (state->mangled_cur[0] == p->abbrev[0] && - state->mangled_cur[1] == p->abbrev[1]) { - MaybeAppend(state, "operator"); - if (IsLower(*p->real_name)) { // new, delete, etc. - MaybeAppend(state, " "); - } - MaybeAppend(state, p->real_name); - state->mangled_cur += 2; - return true; - } - } - return false; -} - -// ::= TV -// ::= TT -// ::= TI -// ::= TS -// ::= Tc <(base) encoding> -// ::= GV <(object) name> -// ::= T <(base) encoding> -// G++ extensions: -// ::= TC <(offset) number> _ <(base) type> -// ::= TF -// ::= TJ -// ::= GR -// ::= GA -// ::= Th <(base) encoding> -// ::= Tv <(base) encoding> -// -// Note: we don't care much about them since they don't appear in -// stack traces. The are special data. -static bool ParseSpecialName(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'T') && - ParseCharClass(state, "VTIS") && - ParseType(state)) { - return true; - } - *state = copy; - - if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) && - ParseCallOffset(state) && ParseEncoding(state)) { - return true; - } - *state = copy; - - if (ParseTwoCharToken(state, "GV") && - ParseName(state)) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) && - ParseEncoding(state)) { - return true; - } - *state = copy; - - // G++ extensions - if (ParseTwoCharToken(state, "TC") && ParseType(state) && - ParseNumber(state, NULL) && ParseOneCharToken(state, '_') && - DisableAppend(state) && - ParseType(state)) { - RestoreAppend(state, copy.append); - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") && - ParseType(state)) { - return true; - } - *state = copy; - - if (ParseTwoCharToken(state, "GR") && ParseName(state)) { - return true; - } - *state = copy; - - if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") && - ParseCallOffset(state) && ParseEncoding(state)) { - return true; - } - *state = copy; - return false; -} - -// ::= h _ -// ::= v _ -static bool ParseCallOffset(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'h') && - ParseNVOffset(state) && ParseOneCharToken(state, '_')) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'v') && - ParseVOffset(state) && ParseOneCharToken(state, '_')) { - return true; - } - *state = copy; - - return false; -} - -// ::= <(offset) number> -static bool ParseNVOffset(State *state) { - return ParseNumber(state, NULL); -} - -// ::= <(offset) number> _ <(virtual offset) number> -static bool ParseVOffset(State *state) { - State copy = *state; - if (ParseNumber(state, NULL) && ParseOneCharToken(state, '_') && - ParseNumber(state, NULL)) { - return true; - } - *state = copy; - return false; -} - -// ::= C1 | C2 | C3 -// ::= D0 | D1 | D2 -static bool ParseCtorDtorName(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'C') && - ParseCharClass(state, "123")) { - const char * const prev_name = state->prev_name; - const int prev_name_length = state->prev_name_length; - MaybeAppendWithLength(state, prev_name, prev_name_length); - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'D') && - ParseCharClass(state, "012")) { - const char * const prev_name = state->prev_name; - const int prev_name_length = state->prev_name_length; - MaybeAppend(state, "~"); - MaybeAppendWithLength(state, prev_name, prev_name_length); - return true; - } - *state = copy; - return false; -} - -// ::= -// ::= P # pointer-to -// ::= R # reference-to -// ::= O # rvalue reference-to (C++0x) -// ::= C # complex pair (C 2000) -// ::= G # imaginary (C 2000) -// ::= U # vendor extended type qualifier -// ::= -// ::= -// ::= -// ::= -// ::= -// ::= -// ::= -// ::= -// ::= Dp # pack expansion of (C++0x) -// ::= Dt E # decltype of an id-expression or class -// # member access (C++0x) -// ::= DT E # decltype of an expression (C++0x) -// -static bool ParseType(State *state) { - // We should check CV-qualifers, and PRGC things first. - State copy = *state; - if (ParseCVQualifiers(state) && ParseType(state)) { - return true; - } - *state = copy; - - if (ParseCharClass(state, "OPRCG") && ParseType(state)) { - return true; - } - *state = copy; - - if (ParseTwoCharToken(state, "Dp") && ParseType(state)) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") && - ParseExpression(state) && ParseOneCharToken(state, 'E')) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'U') && ParseSourceName(state) && - ParseType(state)) { - return true; - } - *state = copy; - - if (ParseBuiltinType(state) || - ParseFunctionType(state) || - ParseClassEnumType(state) || - ParseArrayType(state) || - ParsePointerToMemberType(state) || - ParseSubstitution(state)) { - return true; - } - - if (ParseTemplateTemplateParam(state) && - ParseTemplateArgs(state)) { - return true; - } - *state = copy; - - // Less greedy than . - if (ParseTemplateParam(state)) { - return true; - } - - return false; -} - -// ::= [r] [V] [K] -// We don't allow empty to avoid infinite loop in -// ParseType(). -static bool ParseCVQualifiers(State *state) { - int num_cv_qualifiers = 0; - num_cv_qualifiers += ParseOneCharToken(state, 'r'); - num_cv_qualifiers += ParseOneCharToken(state, 'V'); - num_cv_qualifiers += ParseOneCharToken(state, 'K'); - return num_cv_qualifiers > 0; -} - -// ::= v, etc. -// ::= u -static bool ParseBuiltinType(State *state) { - const AbbrevPair *p; - for (p = kBuiltinTypeList; p->abbrev != NULL; ++p) { - if (state->mangled_cur[0] == p->abbrev[0]) { - MaybeAppend(state, p->real_name); - ++state->mangled_cur; - return true; - } - } - - State copy = *state; - if (ParseOneCharToken(state, 'u') && ParseSourceName(state)) { - return true; - } - *state = copy; - return false; -} - -// ::= F [Y] E -static bool ParseFunctionType(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'F') && - Optional(ParseOneCharToken(state, 'Y')) && - ParseBareFunctionType(state) && ParseOneCharToken(state, 'E')) { - return true; - } - *state = copy; - return false; -} - -// ::= <(signature) type>+ -static bool ParseBareFunctionType(State *state) { - State copy = *state; - DisableAppend(state); - if (OneOrMore(ParseType, state)) { - RestoreAppend(state, copy.append); - MaybeAppend(state, "()"); - return true; - } - *state = copy; - return false; -} - -// ::= -static bool ParseClassEnumType(State *state) { - return ParseName(state); -} - -// ::= A <(positive dimension) number> _ <(element) type> -// ::= A [<(dimension) expression>] _ <(element) type> -static bool ParseArrayType(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'A') && ParseNumber(state, NULL) && - ParseOneCharToken(state, '_') && ParseType(state)) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) && - ParseOneCharToken(state, '_') && ParseType(state)) { - return true; - } - *state = copy; - return false; -} - -// ::= M <(class) type> <(member) type> -static bool ParsePointerToMemberType(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'M') && ParseType(state) && - ParseType(state)) { - return true; - } - *state = copy; - return false; -} - -// ::= T_ -// ::= T _ -static bool ParseTemplateParam(State *state) { - if (ParseTwoCharToken(state, "T_")) { - MaybeAppend(state, "?"); // We don't support template substitutions. - return true; - } - - State copy = *state; - if (ParseOneCharToken(state, 'T') && ParseNumber(state, NULL) && - ParseOneCharToken(state, '_')) { - MaybeAppend(state, "?"); // We don't support template substitutions. - return true; - } - *state = copy; - return false; -} - - -// ::= -// ::= -static bool ParseTemplateTemplateParam(State *state) { - return (ParseTemplateParam(state) || - ParseSubstitution(state)); -} - -// ::= I + E -static bool ParseTemplateArgs(State *state) { - State copy = *state; - DisableAppend(state); - if (ParseOneCharToken(state, 'I') && - OneOrMore(ParseTemplateArg, state) && - ParseOneCharToken(state, 'E')) { - RestoreAppend(state, copy.append); - MaybeAppend(state, "<>"); - return true; - } - *state = copy; - return false; -} - -// ::= -// ::= -// ::= I * E # argument pack -// ::= J * E # argument pack -// ::= X E -static bool ParseTemplateArg(State *state) { - State copy = *state; - if ((ParseOneCharToken(state, 'I') || ParseOneCharToken(state, 'J')) && - ZeroOrMore(ParseTemplateArg, state) && - ParseOneCharToken(state, 'E')) { - return true; - } - *state = copy; - - if (ParseType(state) || - ParseExprPrimary(state)) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'X') && ParseExpression(state) && - ParseOneCharToken(state, 'E')) { - return true; - } - *state = copy; - return false; -} - -// ::= -// ::= -// ::= -// ::= -// ::= -// -// ::= st -// ::= sr -// ::= sr -static bool ParseExpression(State *state) { - if (ParseTemplateParam(state) || ParseExprPrimary(state)) { - return true; - } - - State copy = *state; - if (ParseOperatorName(state) && - ParseExpression(state) && - ParseExpression(state) && - ParseExpression(state)) { - return true; - } - *state = copy; - - if (ParseOperatorName(state) && - ParseExpression(state) && - ParseExpression(state)) { - return true; - } - *state = copy; - - if (ParseOperatorName(state) && - ParseExpression(state)) { - return true; - } - *state = copy; - - if (ParseTwoCharToken(state, "st") && ParseType(state)) { - return true; - } - *state = copy; - - if (ParseTwoCharToken(state, "sr") && ParseType(state) && - ParseUnqualifiedName(state) && - ParseTemplateArgs(state)) { - return true; - } - *state = copy; - - if (ParseTwoCharToken(state, "sr") && ParseType(state) && - ParseUnqualifiedName(state)) { - return true; - } - *state = copy; - return false; -} - -// ::= L <(value) number> E -// ::= L <(value) float> E -// ::= L E -// // A bug in g++'s C++ ABI version 2 (-fabi-version=2). -// ::= LZ E -static bool ParseExprPrimary(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'L') && ParseType(state) && - ParseNumber(state, NULL) && - ParseOneCharToken(state, 'E')) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'L') && ParseType(state) && - ParseFloatNumber(state) && - ParseOneCharToken(state, 'E')) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'L') && ParseMangledName(state) && - ParseOneCharToken(state, 'E')) { - return true; - } - *state = copy; - - if (ParseTwoCharToken(state, "LZ") && ParseEncoding(state) && - ParseOneCharToken(state, 'E')) { - return true; - } - *state = copy; - - return false; -} - -// := Z <(function) encoding> E <(entity) name> -// [] -// := Z <(function) encoding> E s [] -static bool ParseLocalName(State *state) { - State copy = *state; - if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) && - ParseOneCharToken(state, 'E') && MaybeAppend(state, "::") && - ParseName(state) && Optional(ParseDiscriminator(state))) { - return true; - } - *state = copy; - - if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) && - ParseTwoCharToken(state, "Es") && Optional(ParseDiscriminator(state))) { - return true; - } - *state = copy; - return false; -} - -// := _ <(non-negative) number> -static bool ParseDiscriminator(State *state) { - State copy = *state; - if (ParseOneCharToken(state, '_') && ParseNumber(state, NULL)) { - return true; - } - *state = copy; - return false; -} - -// ::= S_ -// ::= S _ -// ::= St, etc. -static bool ParseSubstitution(State *state) { - if (ParseTwoCharToken(state, "S_")) { - MaybeAppend(state, "?"); // We don't support substitutions. - return true; - } - - State copy = *state; - if (ParseOneCharToken(state, 'S') && ParseSeqId(state) && - ParseOneCharToken(state, '_')) { - MaybeAppend(state, "?"); // We don't support substitutions. - return true; - } - *state = copy; - - // Expand abbreviations like "St" => "std". - if (ParseOneCharToken(state, 'S')) { - const AbbrevPair *p; - for (p = kSubstitutionList; p->abbrev != NULL; ++p) { - if (state->mangled_cur[0] == p->abbrev[1]) { - MaybeAppend(state, "std"); - if (p->real_name[0] != '\0') { - MaybeAppend(state, "::"); - MaybeAppend(state, p->real_name); - } - ++state->mangled_cur; - return true; - } - } - } - *state = copy; - return false; -} - -// Parse , optionally followed by either a function-clone suffix -// or version suffix. Returns true only if all of "mangled_cur" was consumed. -static bool ParseTopLevelMangledName(State *state) { - if (ParseMangledName(state)) { - if (state->mangled_cur[0] != '\0') { - // Drop trailing function clone suffix, if any. - if (IsFunctionCloneSuffix(state->mangled_cur)) { - return true; - } - // Append trailing version suffix if any. - // ex. _Z3foo@@GLIBCXX_3.4 - if (state->mangled_cur[0] == '@') { - MaybeAppend(state, state->mangled_cur); - return true; - } - return false; // Unconsumed suffix. - } - return true; - } - return false; -} -#endif - -// The demangler entry point. -bool Demangle(const char *mangled, char *out, int out_size) { -#if defined(OS_WINDOWS) - // When built with incremental linking, the Windows debugger - // library provides a more complicated `Symbol->Name` with the - // Incremental Linking Table offset, which looks like - // `@ILT+1105(?func@Foo@@SAXH@Z)`. However, the demangler expects - // only the mangled symbol, `?func@Foo@@SAXH@Z`. Fortunately, the - // mangled symbol is guaranteed not to have parentheses, - // so we search for `(` and extract up to `)`. - // - // Since we may be in a signal handler here, we cannot use `std::string`. - char buffer[1024]; // Big enough for a sane symbol. - const char *lparen = strchr(mangled, '('); - if (lparen) { - // Extract the string `(?...)` - const char *rparen = strchr(lparen, ')'); - size_t length = rparen - lparen - 1; - strncpy(buffer, lparen + 1, length); - buffer[length] = '\0'; - mangled = buffer; - } // Else the symbol wasn't inside a set of parentheses - // We use the ANSI version to ensure the string type is always `char *`. - return UnDecorateSymbolName(mangled, out, out_size, UNDNAME_COMPLETE); -#else - State state; - InitState(&state, mangled, out, out_size); - return ParseTopLevelMangledName(&state) && !state.overflowed; -#endif -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle.h deleted file mode 100644 index 991b6ffcf2e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle.h +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Satoru Takabayashi -// -// An async-signal-safe and thread-safe demangler for Itanium C++ ABI -// (aka G++ V3 ABI). - -// The demangler is implemented to be used in async signal handlers to -// symbolize stack traces. We cannot use libstdc++'s -// abi::__cxa_demangle() in such signal handlers since it's not async -// signal safe (it uses malloc() internally). -// -// Note that this demangler doesn't support full demangling. More -// specifically, it doesn't print types of function parameters and -// types of template arguments. It just skips them. However, it's -// still very useful to extract basic information such as class, -// function, constructor, destructor, and operator names. -// -// See the implementation note in demangle.cc if you are interested. -// -// Example: -// -// | Mangled Name | The Demangler | abi::__cxa_demangle() -// |---------------|---------------|----------------------- -// | _Z1fv | f() | f() -// | _Z1fi | f() | f(int) -// | _Z3foo3bar | foo() | foo(bar) -// | _Z1fIiEvi | f<>() | void f(int) -// | _ZN1N1fE | N::f | N::f -// | _ZN3Foo3BarEv | Foo::Bar() | Foo::Bar() -// | _Zrm1XS_" | operator%() | operator%(X, X) -// | _ZN3FooC1Ev | Foo::Foo() | Foo::Foo() -// | _Z1fSs | f() | f(std::basic_string, -// | | | std::allocator >) -// -// See the unit test for more examples. -// -// Note: we might want to write demanglers for ABIs other than Itanium -// C++ ABI in the future. -// - -#ifndef BASE_DEMANGLE_H_ -#define BASE_DEMANGLE_H_ - -#include "config.h" -#include "glog/logging.h" - -_START_GOOGLE_NAMESPACE_ - -// Demangle "mangled". On success, return true and write the -// demangled symbol name to "out". Otherwise, return false. -// "out" is modified even if demangling is unsuccessful. -bool GOOGLE_GLOG_DLL_DECL Demangle(const char *mangled, char *out, int out_size); - -_END_GOOGLE_NAMESPACE_ - -#endif // BASE_DEMANGLE_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle_unittest.cc deleted file mode 100644 index be483411f1a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle_unittest.cc +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Satoru Takabayashi -// -// Unit tests for functions in demangle.c. - -#include "utilities.h" - -#include -#include -#include -#include "glog/logging.h" -#include "demangle.h" -#include "googletest.h" -#include "config.h" - -#ifdef HAVE_LIB_GFLAGS -#include -using namespace GFLAGS_NAMESPACE; -#endif - -GLOG_DEFINE_bool(demangle_filter, false, - "Run demangle_unittest in filter mode"); - -using namespace std; -using namespace GOOGLE_NAMESPACE; - -// A wrapper function for Demangle() to make the unit test simple. -static const char *DemangleIt(const char * const mangled) { - static char demangled[4096]; - if (Demangle(mangled, demangled, sizeof(demangled))) { - return demangled; - } else { - return mangled; - } -} - -#if defined(OS_WINDOWS) - -TEST(Demangle, Windows) { - EXPECT_STREQ( - "public: static void __cdecl Foo::func(int)", - DemangleIt("?func@Foo@@SAXH@Z")); - EXPECT_STREQ( - "public: static void __cdecl Foo::func(int)", - DemangleIt("@ILT+1105(?func@Foo@@SAXH@Z)")); - EXPECT_STREQ( - "int __cdecl foobarArray(int * const)", - DemangleIt("?foobarArray@@YAHQAH@Z")); -} - -#else - -// Test corner cases of bounary conditions. -TEST(Demangle, CornerCases) { - const size_t size = 10; - char tmp[size] = { 0 }; - const char *demangled = "foobar()"; - const char *mangled = "_Z6foobarv"; - EXPECT_TRUE(Demangle(mangled, tmp, sizeof(tmp))); - // sizeof("foobar()") == size - 1 - EXPECT_STREQ(demangled, tmp); - EXPECT_TRUE(Demangle(mangled, tmp, size - 1)); - EXPECT_STREQ(demangled, tmp); - EXPECT_FALSE(Demangle(mangled, tmp, size - 2)); // Not enough. - EXPECT_FALSE(Demangle(mangled, tmp, 1)); - EXPECT_FALSE(Demangle(mangled, tmp, 0)); - EXPECT_FALSE(Demangle(mangled, NULL, 0)); // Should not cause SEGV. -} - -// Test handling of functions suffixed with .clone.N, which is used by GCC -// 4.5.x, and .constprop.N and .isra.N, which are used by GCC 4.6.x. These -// suffixes are used to indicate functions which have been cloned during -// optimization. We ignore these suffixes. -TEST(Demangle, Clones) { - char tmp[20]; - EXPECT_TRUE(Demangle("_ZL3Foov", tmp, sizeof(tmp))); - EXPECT_STREQ("Foo()", tmp); - EXPECT_TRUE(Demangle("_ZL3Foov.clone.3", tmp, sizeof(tmp))); - EXPECT_STREQ("Foo()", tmp); - EXPECT_TRUE(Demangle("_ZL3Foov.constprop.80", tmp, sizeof(tmp))); - EXPECT_STREQ("Foo()", tmp); - EXPECT_TRUE(Demangle("_ZL3Foov.isra.18", tmp, sizeof(tmp))); - EXPECT_STREQ("Foo()", tmp); - EXPECT_TRUE(Demangle("_ZL3Foov.isra.2.constprop.18", tmp, sizeof(tmp))); - EXPECT_STREQ("Foo()", tmp); - // Invalid (truncated), should not demangle. - EXPECT_FALSE(Demangle("_ZL3Foov.clo", tmp, sizeof(tmp))); - // Invalid (.clone. not followed by number), should not demangle. - EXPECT_FALSE(Demangle("_ZL3Foov.clone.", tmp, sizeof(tmp))); - // Invalid (.clone. followed by non-number), should not demangle. - EXPECT_FALSE(Demangle("_ZL3Foov.clone.foo", tmp, sizeof(tmp))); - // Invalid (.constprop. not followed by number), should not demangle. - EXPECT_FALSE(Demangle("_ZL3Foov.isra.2.constprop.", tmp, sizeof(tmp))); -} - -TEST(Demangle, FromFile) { - string test_file = FLAGS_test_srcdir + "/src/demangle_unittest.txt"; - ifstream f(test_file.c_str()); // The file should exist. - EXPECT_FALSE(f.fail()); - - string line; - while (getline(f, line)) { - // Lines start with '#' are considered as comments. - if (line.empty() || line[0] == '#') { - continue; - } - // Each line should contain a mangled name and a demangled name - // separated by '\t'. Example: "_Z3foo\tfoo" - string::size_type tab_pos = line.find('\t'); - EXPECT_NE(string::npos, tab_pos); - string mangled = line.substr(0, tab_pos); - string demangled = line.substr(tab_pos + 1); - EXPECT_EQ(demangled, DemangleIt(mangled.c_str())); - } -} - -#endif - -int main(int argc, char **argv) { -#ifdef HAVE_LIB_GFLAGS - ParseCommandLineFlags(&argc, &argv, true); -#endif - InitGoogleTest(&argc, argv); - - FLAGS_logtostderr = true; - InitGoogleLogging(argv[0]); - if (FLAGS_demangle_filter) { - // Read from cin and write to cout. - string line; - while (getline(cin, line, '\n')) { - cout << DemangleIt(line.c_str()) << endl; - } - return 0; - } else if (argc > 1) { - cout << DemangleIt(argv[1]) << endl; - return 0; - } else { - return RUN_ALL_TESTS(); - } -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle_unittest.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle_unittest.sh deleted file mode 100755 index 91deee2198d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle_unittest.sh +++ /dev/null @@ -1,95 +0,0 @@ -#! /bin/sh -# -# Copyright (c) 2006, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# Author: Satoru Takabayashi -# -# Unit tests for demangle.c with a real binary. - -set -e - -die () { - echo $1 - exit 1 -} - -BINDIR=".libs" -LIBGLOG="$BINDIR/libglog.so" - -DEMANGLER="$BINDIR/demangle_unittest" - -if test -e "$DEMANGLER"; then - # We need shared object. - export LD_LIBRARY_PATH=$BINDIR - export DYLD_LIBRARY_PATH=$BINDIR -else - # For windows - DEMANGLER="./demangle_unittest.exe" - if ! test -e "$DEMANGLER"; then - echo "We coundn't find demangle_unittest binary." - exit 1 - fi -fi - -# Extract C++ mangled symbols from libbase.so. -NM_OUTPUT="demangle.nm" -nm "$LIBGLOG" | perl -nle 'print $1 if /\s(_Z\S+$)/' > "$NM_OUTPUT" - -# Check if mangled symbols exist. If there are none, we quit. -# The binary is more likely compiled with GCC 2.95 or something old. -if ! grep --quiet '^_Z' "$NM_OUTPUT"; then - echo "PASS" - exit 0 -fi - -# Demangle the symbols using our demangler. -DM_OUTPUT="demangle.dm" -GLOG_demangle_filter=1 "$DEMANGLER" --demangle_filter < "$NM_OUTPUT" > "$DM_OUTPUT" - -# Calculate the numbers of lines. -NM_LINES=`wc -l "$NM_OUTPUT" | awk '{ print $1 }'` -DM_LINES=`wc -l "$DM_OUTPUT" | awk '{ print $1 }'` - -# Compare the numbers of lines. They must be the same. -if test "$NM_LINES" != "$DM_LINES"; then - die "$NM_OUTPUT and $DM_OUTPUT don't have the same numbers of lines" -fi - -# Check if mangled symbols exist. They must not exist. -if grep --quiet '^_Z' "$DM_OUTPUT"; then - MANGLED=`grep '^_Z' "$DM_OUTPUT" | wc -l | awk '{ print \$1 }'` - echo "Mangled symbols ($MANGLED out of $NM_LINES) found in $DM_OUTPUT:" - grep '^_Z' "$DM_OUTPUT" - die "Mangled symbols ($MANGLED out of $NM_LINES) found in $DM_OUTPUT" -fi - -# All C++ symbols are demangled successfully. -echo "PASS" -exit 0 diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle_unittest.txt b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle_unittest.txt deleted file mode 100644 index 07e28bce2f8..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/demangle_unittest.txt +++ /dev/null @@ -1,145 +0,0 @@ -# Test caces for demangle_unittest. Each line consists of a -# tab-separated pair of mangled and demangled symbol names. - -# Constructors and destructors. -_ZN3FooC1Ev Foo::Foo() -_ZN3FooD1Ev Foo::~Foo() -_ZNSoD0Ev std::ostream::~ostream() - -# G++ extensions. -_ZTCN10LogMessage9LogStreamE0_So LogMessage::LogStream -_ZTv0_n12_N10LogMessage9LogStreamD0Ev LogMessage::LogStream::~LogStream() -_ZThn4_N7icu_3_410UnicodeSetD0Ev icu_3_4::UnicodeSet::~UnicodeSet() - -# A bug in g++'s C++ ABI version 2 (-fabi-version=2). -_ZN7NSSInfoI5groupjjXadL_Z10getgrgid_rEELZ19nss_getgrgid_r_nameEEC1Ei NSSInfo<>::NSSInfo() - -# C linkage symbol names. Should keep them untouched. -main main -Demangle Demangle -_ZERO _ZERO - -# Cast operator. -_Zcviv operator int() -_ZN3foocviEv foo::operator int() - -# Versioned symbols. -_Z3Foo@GLIBCXX_3.4 Foo@GLIBCXX_3.4 -_Z3Foo@@GLIBCXX_3.4 Foo@@GLIBCXX_3.4 - -# Abbreviations. -_ZNSaE std::allocator -_ZNSbE std::basic_string -_ZNSdE std::iostream -_ZNSiE std::istream -_ZNSoE std::ostream -_ZNSsE std::string - -# Substitutions. We just replace them with ?. -_ZN3fooS_E foo::? -_ZN3foo3barS0_E foo::bar::? -_ZNcvT_IiEEv operator ?<>() - -# "<< <" case. -_ZlsI3fooE operator<< <> - -# ABI tags. -_Z1AB3barB3foo A -_ZN3fooL3barB5cxx11E foo::bar - -# Random things we found interesting. -_ZN3FooISt6vectorISsSaISsEEEclEv Foo<>::operator()() -_ZTI9Callback1IiE Callback1<> -_ZN7icu_3_47UMemorynwEj icu_3_4::UMemory::operator new() -_ZNSt6vectorIbE9push_backE std::vector<>::push_back -_ZNSt6vectorIbSaIbEE9push_backEb std::vector<>::push_back() -_ZlsRSoRK15PRIVATE_Counter operator<<() -_ZSt6fill_nIPPN9__gnu_cxx15_Hashtable_nodeISt4pairIKPKcjEEEjS8_ET_SA_T0_RKT1_ std::fill_n<>() -_ZZ3FoovE3Bar Foo()::Bar -_ZGVZ7UpTimervE8up_timer UpTimer()::up_timer - -# Test cases from gcc-4.1.0/libstdc++-v3/testsuite/demangle. -# Collected by: -# % grep verify_demangle **/*.cc | perl -nle 'print $1 if /"(_Z.*?)"/' | -# sort | uniq -# -# Note that the following symbols are invalid. -# That's why they are not demangled. -# - _ZNZN1N1fEiE1X1gE -# - _ZNZN1N1fEiE1X1gEv -# - _Z1xINiEE -_Z1fA37_iPS_ f() -_Z1fAszL_ZZNK1N1A1fEvE3foo_0E_i f() -_Z1fI1APS0_PKS0_EvT_T0_T1_PA4_S3_M1CS8_ f<>() -_Z1fI1XENT_1tES2_ f<>() -_Z1fI1XEvPVN1AIT_E1TE f<>() -_Z1fILi1ELc120EEv1AIXplT_cviLd4028ae147ae147aeEEE f<>() -_Z1fILi1ELc120EEv1AIXplT_cviLf3f800000EEE f<>() -_Z1fILi5E1AEvN1CIXqugtT_Li0ELi1ELi2EEE1qE f<>() -_Z1fILi5E1AEvN1CIXstN1T1tEEXszsrS2_1tEE1qE f<>() -_Z1fILi5EEvN1AIXcvimlT_Li22EEE1qE f<>() -_Z1fIiEvi f<>() -_Z1fKPFiiE f() -_Z1fM1AFivEPS0_ f() -_Z1fM1AKFivE f() -_Z1fM1AKFvvE f() -_Z1fPFPA1_ivE f() -_Z1fPFYPFiiEiE f() -_Z1fPFvvEM1SFvvE f() -_Z1fPKM1AFivE f() -_Z1fi f() -_Z1fv f() -_Z1jM1AFivEPS1_ j() -_Z1rM1GFivEMS_KFivES_M1HFivES1_4whatIKS_E5what2IS8_ES3_ r() -_Z1sPA37_iPS0_ s() -_Z1xINiEE _Z1xINiEE -_Z3absILi11EEvv abs<>() -_Z3foo3bar foo() -_Z3foo5Hello5WorldS0_S_ foo() -_Z3fooA30_A_i foo() -_Z3fooIA6_KiEvA9_KT_rVPrS4_ foo<>() -_Z3fooILi2EEvRAplT_Li1E_i foo<>() -_Z3fooIiFvdEiEvv foo<>() -_Z3fooPM2ABi foo() -_Z3fooc foo() -_Z3fooiPiPS_PS0_PS1_PS2_PS3_PS4_PS5_PS6_PS7_PS8_PS9_PSA_PSB_PSC_ foo() -_Z3kooPA28_A30_i koo() -_Z4makeI7FactoryiET_IT0_Ev make<>() -_Z5firstI3DuoEvS0_ first<>() -_Z5firstI3DuoEvT_ first<>() -_Z9hairyfuncM1YKFPVPFrPA2_PM1XKFKPA3_ilEPcEiE hairyfunc() -_ZGVN5libcw24_GLOBAL__N_cbll.cc0ZhUKa23compiler_bug_workaroundISt6vectorINS_13omanip_id_tctINS_5debug32memblk_types_manipulator_data_ctEEESaIS6_EEE3idsE libcw::(anonymous namespace)::compiler_bug_workaround<>::ids -_ZN12libcw_app_ct10add_optionIS_EEvMT_FvPKcES3_cS3_S3_ libcw_app_ct::add_option<>() -_ZN1AIfEcvT_IiEEv A<>::operator ?<>() -_ZN1N1TIiiE2mfES0_IddE N::T<>::mf() -_ZN1N1fE N::f -_ZN1f1fE f::f -_ZN3FooIA4_iE3barE Foo<>::bar -_ZN5Arena5levelE Arena::level -_ZN5StackIiiE5levelE Stack<>::level -_ZN5libcw5debug13cwprint_usingINS_9_private_12GlobalObjectEEENS0_17cwprint_using_tctIT_EERKS5_MS5_KFvRSt7ostreamE libcw::debug::cwprint_using<>() -_ZN6System5Sound4beepEv System::Sound::beep() -_ZNKSt14priority_queueIP27timer_event_request_base_ctSt5dequeIS1_SaIS1_EE13timer_greaterE3topEv std::priority_queue<>::top() -_ZNKSt15_Deque_iteratorIP15memory_block_stRKS1_PS2_EeqERKS5_ std::_Deque_iterator<>::operator==() -_ZNKSt17__normal_iteratorIPK6optionSt6vectorIS0_SaIS0_EEEmiERKS6_ std::__normal_iterator<>::operator-() -_ZNSbIcSt11char_traitsIcEN5libcw5debug27no_alloc_checking_allocatorEE12_S_constructIPcEES6_T_S7_RKS3_ std::basic_string<>::_S_construct<>() -_ZNSt13_Alloc_traitsISbIcSt18string_char_traitsIcEN5libcw5debug9_private_17allocator_adaptorIcSt24__default_alloc_templateILb0ELi327664EELb1EEEENS5_IS9_S7_Lb1EEEE15_S_instancelessE std::_Alloc_traits<>::_S_instanceless -_ZNSt3_In4wardE std::_In::ward -_ZNZN1N1fEiE1X1gE _ZNZN1N1fEiE1X1gE -_ZNZN1N1fEiE1X1gEv _ZNZN1N1fEiE1X1gEv -_ZSt1BISt1DIP1ARKS2_PS3_ES0_IS2_RS2_PS2_ES2_ET0_T_SB_SA_PT1_ std::B<>() -_ZSt5state std::state -_ZTI7a_class a_class -_ZZN1N1fEiE1p N::f()::p -_ZZN1N1fEiEs N::f() -_ZlsRK1XS1_ operator<<() -_ZlsRKU3fooU4bart1XS0_ operator<<() -_ZlsRKU3fooU4bart1XS2_ operator<<() -_ZlsRSoRKSs operator<<() -_ZngILi42EEvN1AIXplT_Li2EEE1TE operator-<>() -_ZplR1XS0_ operator+() -_Zrm1XS_ operator%() - -# Template argument packs can start with I or J. -_Z3addIIiEEvDpT_ add<>() -_Z3addIJiEEvDpT_ add<>() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/log_severity.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/log_severity.h deleted file mode 100644 index 99945a426da..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/log_severity.h +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef BASE_LOG_SEVERITY_H__ -#define BASE_LOG_SEVERITY_H__ - -// Annoying stuff for windows -- makes sure clients can import these functions -#ifndef GOOGLE_GLOG_DLL_DECL -# if defined(_WIN32) && !defined(__CYGWIN__) -# define GOOGLE_GLOG_DLL_DECL __declspec(dllimport) -# else -# define GOOGLE_GLOG_DLL_DECL -# endif -#endif - -// Variables of type LogSeverity are widely taken to lie in the range -// [0, NUM_SEVERITIES-1]. Be careful to preserve this assumption if -// you ever need to change their values or add a new severity. -typedef int LogSeverity; - -const int GLOG_INFO = 0, GLOG_WARNING = 1, GLOG_ERROR = 2, GLOG_FATAL = 3, - NUM_SEVERITIES = 4; -#ifndef GLOG_NO_ABBREVIATED_SEVERITIES -# ifdef ERROR -# error ERROR macro is defined. Define GLOG_NO_ABBREVIATED_SEVERITIES before including logging.h. See the document for detail. -# endif -const int INFO = GLOG_INFO, WARNING = GLOG_WARNING, - ERROR = GLOG_ERROR, FATAL = GLOG_FATAL; -#endif - -// DFATAL is FATAL in debug mode, ERROR in normal mode -#ifdef NDEBUG -#define DFATAL_LEVEL ERROR -#else -#define DFATAL_LEVEL FATAL -#endif - -extern GOOGLE_GLOG_DLL_DECL const char* const LogSeverityNames[NUM_SEVERITIES]; - -// NDEBUG usage helpers related to (RAW_)DCHECK: -// -// DEBUG_MODE is for small !NDEBUG uses like -// if (DEBUG_MODE) foo.CheckThatFoo(); -// instead of substantially more verbose -// #ifndef NDEBUG -// foo.CheckThatFoo(); -// #endif -// -// IF_DEBUG_MODE is for small !NDEBUG uses like -// IF_DEBUG_MODE( string error; ) -// DCHECK(Foo(&error)) << error; -// instead of substantially more verbose -// #ifndef NDEBUG -// string error; -// DCHECK(Foo(&error)) << error; -// #endif -// -#ifdef NDEBUG -enum { DEBUG_MODE = 0 }; -#define IF_DEBUG_MODE(x) -#else -enum { DEBUG_MODE = 1 }; -#define IF_DEBUG_MODE(x) x -#endif - -#endif // BASE_LOG_SEVERITY_H__ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/logging.h.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/logging.h.in deleted file mode 100644 index 9968b96d317..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/logging.h.in +++ /dev/null @@ -1,1662 +0,0 @@ -// Copyright (c) 1999, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Ray Sidney -// -// This file contains #include information about logging-related stuff. -// Pretty much everybody needs to #include this file so that they can -// log various happenings. -// -#ifndef _LOGGING_H_ -#define _LOGGING_H_ - -#include -#include -#include -#include -#include -#include -#include -#if @ac_cv_have_unistd_h@ -# include -#endif -#include - -#if defined(_MSC_VER) -#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \ - __pragma(warning(disable:n)) -#define GLOG_MSVC_POP_WARNING() __pragma(warning(pop)) -#else -#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) -#define GLOG_MSVC_POP_WARNING() -#endif - -// Annoying stuff for windows -- makes sure clients can import these functions -#ifndef GOOGLE_GLOG_DLL_DECL -# if defined(_WIN32) && !defined(__CYGWIN__) -# define GOOGLE_GLOG_DLL_DECL __declspec(dllimport) -# else -# define GOOGLE_GLOG_DLL_DECL -# endif -#endif - -// We care a lot about number of bits things take up. Unfortunately, -// systems define their bit-specific ints in a lot of different ways. -// We use our own way, and have a typedef to get there. -// Note: these commands below may look like "#if 1" or "#if 0", but -// that's because they were constructed that way at ./configure time. -// Look at logging.h.in to see how they're calculated (based on your config). -#if @ac_cv_have_stdint_h@ -#include // the normal place uint16_t is defined -#endif -#if @ac_cv_have_systypes_h@ -#include // the normal place u_int16_t is defined -#endif -#if @ac_cv_have_inttypes_h@ -#include // a third place for uint16_t or u_int16_t -#endif - -#if @ac_cv_have_libgflags@ -#include -#endif - -@ac_google_start_namespace@ - -#if @ac_cv_have_uint16_t@ // the C99 format -typedef int32_t int32; -typedef uint32_t uint32; -typedef int64_t int64; -typedef uint64_t uint64; -#elif @ac_cv_have_u_int16_t@ // the BSD format -typedef int32_t int32; -typedef u_int32_t uint32; -typedef int64_t int64; -typedef u_int64_t uint64; -#elif @ac_cv_have___uint16@ // the windows (vc7) format -typedef __int32 int32; -typedef unsigned __int32 uint32; -typedef __int64 int64; -typedef unsigned __int64 uint64; -#else -#error Do not know how to define a 32-bit integer quantity on your system -#endif - -@ac_google_end_namespace@ - -// The global value of GOOGLE_STRIP_LOG. All the messages logged to -// LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed. -// If it can be determined at compile time that the message will not be -// printed, the statement will be compiled out. -// -// Example: to strip out all INFO and WARNING messages, use the value -// of 2 below. To make an exception for WARNING messages from a single -// file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including -// base/logging.h -#ifndef GOOGLE_STRIP_LOG -#define GOOGLE_STRIP_LOG 0 -#endif - -// GCC can be told that a certain branch is not likely to be taken (for -// instance, a CHECK failure), and use that information in static analysis. -// Giving it this information can help it optimize for the common case in -// the absence of better information (ie. -fprofile-arcs). -// -#ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN -#if @ac_cv_have___builtin_expect@ -#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0)) -#else -#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x -#endif -#endif - -#ifndef GOOGLE_PREDICT_FALSE -#if @ac_cv_have___builtin_expect@ -#define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0)) -#else -#define GOOGLE_PREDICT_FALSE(x) x -#endif -#endif - -#ifndef GOOGLE_PREDICT_TRUE -#if @ac_cv_have___builtin_expect@ -#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) -#else -#define GOOGLE_PREDICT_TRUE(x) x -#endif -#endif - - -// Make a bunch of macros for logging. The way to log things is to stream -// things to LOG(). E.g., -// -// LOG(INFO) << "Found " << num_cookies << " cookies"; -// -// You can capture log messages in a string, rather than reporting them -// immediately: -// -// vector errors; -// LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num; -// -// This pushes back the new error onto 'errors'; if given a NULL pointer, -// it reports the error via LOG(ERROR). -// -// You can also do conditional logging: -// -// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; -// -// You can also do occasional logging (log every n'th occurrence of an -// event): -// -// LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie"; -// -// The above will cause log messages to be output on the 1st, 11th, 21st, ... -// times it is executed. Note that the special google::COUNTER value is used -// to identify which repetition is happening. -// -// You can also do occasional conditional logging (log every n'th -// occurrence of an event, when condition is satisfied): -// -// LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER -// << "th big cookie"; -// -// You can log messages the first N times your code executes a line. E.g. -// -// LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie"; -// -// Outputs log messages for the first 20 times it is executed. -// -// Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available. -// These log to syslog as well as to the normal logs. If you use these at -// all, you need to be aware that syslog can drastically reduce performance, -// especially if it is configured for remote logging! Don't use these -// unless you fully understand this and have a concrete need to use them. -// Even then, try to minimize your use of them. -// -// There are also "debug mode" logging macros like the ones above: -// -// DLOG(INFO) << "Found cookies"; -// -// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; -// -// DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie"; -// -// All "debug mode" logging is compiled away to nothing for non-debug mode -// compiles. -// -// We also have -// -// LOG_ASSERT(assertion); -// DLOG_ASSERT(assertion); -// -// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion; -// -// There are "verbose level" logging macros. They look like -// -// VLOG(1) << "I'm printed when you run the program with --v=1 or more"; -// VLOG(2) << "I'm printed when you run the program with --v=2 or more"; -// -// These always log at the INFO log level (when they log at all). -// The verbose logging can also be turned on module-by-module. For instance, -// --vmodule=mapreduce=2,file=1,gfs*=3 --v=0 -// will cause: -// a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc} -// b. VLOG(1) and lower messages to be printed from file.{h,cc} -// c. VLOG(3) and lower messages to be printed from files prefixed with "gfs" -// d. VLOG(0) and lower messages to be printed from elsewhere -// -// The wildcarding functionality shown by (c) supports both '*' (match -// 0 or more characters) and '?' (match any single character) wildcards. -// -// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as -// -// if (VLOG_IS_ON(2)) { -// // do some logging preparation and logging -// // that can't be accomplished with just VLOG(2) << ...; -// } -// -// There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level" -// condition macros for sample cases, when some extra computation and -// preparation for logs is not needed. -// VLOG_IF(1, (size > 1024)) -// << "I'm printed when size is more than 1024 and when you run the " -// "program with --v=1 or more"; -// VLOG_EVERY_N(1, 10) -// << "I'm printed every 10th occurrence, and when you run the program " -// "with --v=1 or more. Present occurence is " << google::COUNTER; -// VLOG_IF_EVERY_N(1, (size > 1024), 10) -// << "I'm printed on every 10th occurence of case when size is more " -// " than 1024, when you run the program with --v=1 or more. "; -// "Present occurence is " << google::COUNTER; -// -// The supported severity levels for macros that allow you to specify one -// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL. -// Note that messages of a given severity are logged not only in the -// logfile for that severity, but also in all logfiles of lower severity. -// E.g., a message of severity FATAL will be logged to the logfiles of -// severity FATAL, ERROR, WARNING, and INFO. -// -// There is also the special severity of DFATAL, which logs FATAL in -// debug mode, ERROR in normal mode. -// -// Very important: logging a message at the FATAL severity level causes -// the program to terminate (after the message is logged). -// -// Unless otherwise specified, logs will be written to the filename -// "...log..", followed -// by the date, time, and pid (you can't prevent the date, time, and pid -// from being in the filename). -// -// The logging code takes two flags: -// --v=# set the verbose level -// --logtostderr log all the messages to stderr instead of to logfiles - -// LOG LINE PREFIX FORMAT -// -// Log lines have this form: -// -// Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... -// -// where the fields are defined as follows: -// -// L A single character, representing the log level -// (eg 'I' for INFO) -// mm The month (zero padded; ie May is '05') -// dd The day (zero padded) -// hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds -// threadid The space-padded thread ID as returned by GetTID() -// (this matches the PID on Linux) -// file The file name -// line The line number -// msg The user-supplied message -// -// Example: -// -// I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog -// I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395 -// -// NOTE: although the microseconds are useful for comparing events on -// a single machine, clocks on different machines may not be well -// synchronized. Hence, use caution when comparing the low bits of -// timestamps from different machines. - -#ifndef DECLARE_VARIABLE -#define MUST_UNDEF_GFLAGS_DECLARE_MACROS -#define DECLARE_VARIABLE(type, shorttype, name, tn) \ - namespace fL##shorttype { \ - extern GOOGLE_GLOG_DLL_DECL type FLAGS_##name; \ - } \ - using fL##shorttype::FLAGS_##name - -// bool specialization -#define DECLARE_bool(name) \ - DECLARE_VARIABLE(bool, B, name, bool) - -// int32 specialization -#define DECLARE_int32(name) \ - DECLARE_VARIABLE(@ac_google_namespace@::int32, I, name, int32) - -// Special case for string, because we have to specify the namespace -// std::string, which doesn't play nicely with our FLAG__namespace hackery. -#define DECLARE_string(name) \ - namespace fLS { \ - extern GOOGLE_GLOG_DLL_DECL std::string& FLAGS_##name; \ - } \ - using fLS::FLAGS_##name -#endif - -// Set whether log messages go to stderr instead of logfiles -DECLARE_bool(logtostderr); - -// Set whether log messages go to stderr in addition to logfiles. -DECLARE_bool(alsologtostderr); - -// Set color messages logged to stderr (if supported by terminal). -DECLARE_bool(colorlogtostderr); - -// Log messages at a level >= this flag are automatically sent to -// stderr in addition to log files. -DECLARE_int32(stderrthreshold); - -// Set whether the log prefix should be prepended to each line of output. -DECLARE_bool(log_prefix); - -// Log messages at a level <= this flag are buffered. -// Log messages at a higher level are flushed immediately. -DECLARE_int32(logbuflevel); - -// Sets the maximum number of seconds which logs may be buffered for. -DECLARE_int32(logbufsecs); - -// Log suppression level: messages logged at a lower level than this -// are suppressed. -DECLARE_int32(minloglevel); - -// If specified, logfiles are written into this directory instead of the -// default logging directory. -DECLARE_string(log_dir); - -// Set the log file mode. -DECLARE_int32(logfile_mode); - -// Sets the path of the directory into which to put additional links -// to the log files. -DECLARE_string(log_link); - -DECLARE_int32(v); // in vlog_is_on.cc - -// Sets the maximum log file size (in MB). -DECLARE_int32(max_log_size); - -// Sets whether to avoid logging to the disk if the disk is full. -DECLARE_bool(stop_logging_if_full_disk); - -#ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS -#undef MUST_UNDEF_GFLAGS_DECLARE_MACROS -#undef DECLARE_VARIABLE -#undef DECLARE_bool -#undef DECLARE_int32 -#undef DECLARE_string -#endif - -// Log messages below the GOOGLE_STRIP_LOG level will be compiled away for -// security reasons. See LOG(severtiy) below. - -// A few definitions of macros that don't generate much code. Since -// LOG(INFO) and its ilk are used all over our code, it's -// better to have compact code for these operations. - -#if GOOGLE_STRIP_LOG == 0 -#define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__) -#define LOG_TO_STRING_INFO(message) @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, message) -#else -#define COMPACT_GOOGLE_LOG_INFO @ac_google_namespace@::NullStream() -#define LOG_TO_STRING_INFO(message) @ac_google_namespace@::NullStream() -#endif - -#if GOOGLE_STRIP_LOG <= 1 -#define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING) -#define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, message) -#else -#define COMPACT_GOOGLE_LOG_WARNING @ac_google_namespace@::NullStream() -#define LOG_TO_STRING_WARNING(message) @ac_google_namespace@::NullStream() -#endif - -#if GOOGLE_STRIP_LOG <= 2 -#define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR) -#define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, message) -#else -#define COMPACT_GOOGLE_LOG_ERROR @ac_google_namespace@::NullStream() -#define LOG_TO_STRING_ERROR(message) @ac_google_namespace@::NullStream() -#endif - -#if GOOGLE_STRIP_LOG <= 3 -#define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::LogMessageFatal( \ - __FILE__, __LINE__) -#define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, message) -#else -#define COMPACT_GOOGLE_LOG_FATAL @ac_google_namespace@::NullStreamFatal() -#define LOG_TO_STRING_FATAL(message) @ac_google_namespace@::NullStreamFatal() -#endif - -#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) -#define DCHECK_IS_ON() 0 -#else -#define DCHECK_IS_ON() 1 -#endif - -// For DFATAL, we want to use LogMessage (as opposed to -// LogMessageFatal), to be consistent with the original behavior. -#if !DCHECK_IS_ON() -#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR -#elif GOOGLE_STRIP_LOG <= 3 -#define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL) -#else -#define COMPACT_GOOGLE_LOG_DFATAL @ac_google_namespace@::NullStreamFatal() -#endif - -#define GOOGLE_LOG_INFO(counter) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, &@ac_google_namespace@::LogMessage::SendToLog) -#define SYSLOG_INFO(counter) \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_INFO, counter, \ - &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) -#define GOOGLE_LOG_WARNING(counter) \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \ - &@ac_google_namespace@::LogMessage::SendToLog) -#define SYSLOG_WARNING(counter) \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_WARNING, counter, \ - &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) -#define GOOGLE_LOG_ERROR(counter) \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \ - &@ac_google_namespace@::LogMessage::SendToLog) -#define SYSLOG_ERROR(counter) \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, counter, \ - &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) -#define GOOGLE_LOG_FATAL(counter) \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \ - &@ac_google_namespace@::LogMessage::SendToLog) -#define SYSLOG_FATAL(counter) \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_FATAL, counter, \ - &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) -#define GOOGLE_LOG_DFATAL(counter) \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \ - &@ac_google_namespace@::LogMessage::SendToLog) -#define SYSLOG_DFATAL(counter) \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::DFATAL_LEVEL, counter, \ - &@ac_google_namespace@::LogMessage::SendToSyslogAndLog) - -#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__) -// A very useful logging macro to log windows errors: -#define LOG_SYSRESULT(result) \ - if (FAILED(HRESULT_FROM_WIN32(result))) { \ - LPSTR message = NULL; \ - LPSTR msg = reinterpret_cast(&message); \ - DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \ - FORMAT_MESSAGE_FROM_SYSTEM, \ - 0, result, 0, msg, 100, NULL); \ - if (message_length > 0) { \ - @ac_google_namespace@::LogMessage(__FILE__, __LINE__, @ac_google_namespace@::GLOG_ERROR, 0, \ - &@ac_google_namespace@::LogMessage::SendToLog).stream() \ - << reinterpret_cast(message); \ - LocalFree(message); \ - } \ - } -#endif - -// We use the preprocessor's merging operator, "##", so that, e.g., -// LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny -// subtle difference between ostream member streaming functions (e.g., -// ostream::operator<<(int) and ostream non-member streaming functions -// (e.g., ::operator<<(ostream&, string&): it turns out that it's -// impossible to stream something like a string directly to an unnamed -// ostream. We employ a neat hack by calling the stream() member -// function of LogMessage which seems to avoid the problem. -#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream() -#define SYSLOG(severity) SYSLOG_ ## severity(0).stream() - -@ac_google_start_namespace@ - -// They need the definitions of integer types. -#include "glog/log_severity.h" -#include "glog/vlog_is_on.h" - -// Initialize google's logging library. You will see the program name -// specified by argv0 in log outputs. -GOOGLE_GLOG_DLL_DECL void InitGoogleLogging(const char* argv0); - -// Shutdown google's logging library. -GOOGLE_GLOG_DLL_DECL void ShutdownGoogleLogging(); - -// Install a function which will be called after LOG(FATAL). -GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)()); - -class LogSink; // defined below - -// If a non-NULL sink pointer is given, we push this message to that sink. -// For LOG_TO_SINK we then do normal LOG(severity) logging as well. -// This is useful for capturing messages and passing/storing them -// somewhere more specific than the global log of the process. -// Argument types: -// LogSink* sink; -// LogSeverity severity; -// The cast is to disambiguate NULL arguments. -#define LOG_TO_SINK(sink, severity) \ - @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, \ - @ac_google_namespace@::GLOG_ ## severity, \ - static_cast<@ac_google_namespace@::LogSink*>(sink), true).stream() -#define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \ - @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, \ - @ac_google_namespace@::GLOG_ ## severity, \ - static_cast<@ac_google_namespace@::LogSink*>(sink), false).stream() - -// If a non-NULL string pointer is given, we write this message to that string. -// We then do normal LOG(severity) logging as well. -// This is useful for capturing messages and storing them somewhere more -// specific than the global log of the process. -// Argument types: -// string* message; -// LogSeverity severity; -// The cast is to disambiguate NULL arguments. -// NOTE: LOG(severity) expands to LogMessage().stream() for the specified -// severity. -#define LOG_TO_STRING(severity, message) \ - LOG_TO_STRING_##severity(static_cast(message)).stream() - -// If a non-NULL pointer is given, we push the message onto the end -// of a vector of strings; otherwise, we report it with LOG(severity). -// This is handy for capturing messages and perhaps passing them back -// to the caller, rather than reporting them immediately. -// Argument types: -// LogSeverity severity; -// vector *outvec; -// The cast is to disambiguate NULL arguments. -#define LOG_STRING(severity, outvec) \ - LOG_TO_STRING_##severity(static_cast*>(outvec)).stream() - -#define LOG_IF(severity, condition) \ - static_cast(0), \ - !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) -#define SYSLOG_IF(severity, condition) \ - static_cast(0), \ - !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & SYSLOG(severity) - -#define LOG_ASSERT(condition) \ - LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition -#define SYSLOG_ASSERT(condition) \ - SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition - -// CHECK dies with a fatal error if condition is not true. It is *not* -// controlled by DCHECK_IS_ON(), so the check will be executed regardless of -// compilation mode. Therefore, it is safe to do things like: -// CHECK(fp->Write(x) == 4) -#define CHECK(condition) \ - LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \ - << "Check failed: " #condition " " - -// A container for a string pointer which can be evaluated to a bool - -// true iff the pointer is NULL. -struct CheckOpString { - CheckOpString(std::string* str) : str_(str) { } - // No destructor: if str_ is non-NULL, we're about to LOG(FATAL), - // so there's no point in cleaning up str_. - operator bool() const { - return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL); - } - std::string* str_; -}; - -// Function is overloaded for integral types to allow static const -// integrals declared in classes and not defined to be used as arguments to -// CHECK* macros. It's not encouraged though. -template -inline const T& GetReferenceableValue(const T& t) { return t; } -inline char GetReferenceableValue(char t) { return t; } -inline unsigned char GetReferenceableValue(unsigned char t) { return t; } -inline signed char GetReferenceableValue(signed char t) { return t; } -inline short GetReferenceableValue(short t) { return t; } -inline unsigned short GetReferenceableValue(unsigned short t) { return t; } -inline int GetReferenceableValue(int t) { return t; } -inline unsigned int GetReferenceableValue(unsigned int t) { return t; } -inline long GetReferenceableValue(long t) { return t; } -inline unsigned long GetReferenceableValue(unsigned long t) { return t; } -inline long long GetReferenceableValue(long long t) { return t; } -inline unsigned long long GetReferenceableValue(unsigned long long t) { - return t; -} - -// This is a dummy class to define the following operator. -struct DummyClassToDefineOperator {}; - -@ac_google_end_namespace@ - -// Define global operator<< to declare using ::operator<<. -// This declaration will allow use to use CHECK macros for user -// defined classes which have operator<< (e.g., stl_logging.h). -inline std::ostream& operator<<( - std::ostream& out, const google::DummyClassToDefineOperator&) { - return out; -} - -@ac_google_start_namespace@ - -// This formats a value for a failing CHECK_XX statement. Ordinarily, -// it uses the definition for operator<<, with a few special cases below. -template -inline void MakeCheckOpValueString(std::ostream* os, const T& v) { - (*os) << v; -} - -// Overrides for char types provide readable values for unprintable -// characters. -template <> GOOGLE_GLOG_DLL_DECL -void MakeCheckOpValueString(std::ostream* os, const char& v); -template <> GOOGLE_GLOG_DLL_DECL -void MakeCheckOpValueString(std::ostream* os, const signed char& v); -template <> GOOGLE_GLOG_DLL_DECL -void MakeCheckOpValueString(std::ostream* os, const unsigned char& v); - -// Build the error message string. Specify no inlining for code size. -template -std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) - @ac_cv___attribute___noinline@; - -namespace base { -namespace internal { - -// If "s" is less than base_logging::INFO, returns base_logging::INFO. -// If "s" is greater than base_logging::FATAL, returns -// base_logging::ERROR. Otherwise, returns "s". -LogSeverity NormalizeSeverity(LogSeverity s); - -} // namespace internal - -// A helper class for formatting "expr (V1 vs. V2)" in a CHECK_XX -// statement. See MakeCheckOpString for sample usage. Other -// approaches were considered: use of a template method (e.g., -// base::BuildCheckOpString(exprtext, base::Print, &v1, -// base::Print, &v2), however this approach has complications -// related to volatile arguments and function-pointer arguments). -class GOOGLE_GLOG_DLL_DECL CheckOpMessageBuilder { - public: - // Inserts "exprtext" and " (" to the stream. - explicit CheckOpMessageBuilder(const char *exprtext); - // Deletes "stream_". - ~CheckOpMessageBuilder(); - // For inserting the first variable. - std::ostream* ForVar1() { return stream_; } - // For inserting the second variable (adds an intermediate " vs. "). - std::ostream* ForVar2(); - // Get the result (inserts the closing ")"). - std::string* NewString(); - - private: - std::ostringstream *stream_; -}; - -} // namespace base - -template -std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) { - base::CheckOpMessageBuilder comb(exprtext); - MakeCheckOpValueString(comb.ForVar1(), v1); - MakeCheckOpValueString(comb.ForVar2(), v2); - return comb.NewString(); -} - -// Helper functions for CHECK_OP macro. -// The (int, int) specialization works around the issue that the compiler -// will not instantiate the template version of the function on values of -// unnamed enum type - see comment below. -#define DEFINE_CHECK_OP_IMPL(name, op) \ - template \ - inline std::string* name##Impl(const T1& v1, const T2& v2, \ - const char* exprtext) { \ - if (GOOGLE_PREDICT_TRUE(v1 op v2)) return NULL; \ - else return MakeCheckOpString(v1, v2, exprtext); \ - } \ - inline std::string* name##Impl(int v1, int v2, const char* exprtext) { \ - return name##Impl(v1, v2, exprtext); \ - } - -// We use the full name Check_EQ, Check_NE, etc. in case the file including -// base/logging.h provides its own #defines for the simpler names EQ, NE, etc. -// This happens if, for example, those are used as token names in a -// yacc grammar. -DEFINE_CHECK_OP_IMPL(Check_EQ, ==) // Compilation error with CHECK_EQ(NULL, x)? -DEFINE_CHECK_OP_IMPL(Check_NE, !=) // Use CHECK(x == NULL) instead. -DEFINE_CHECK_OP_IMPL(Check_LE, <=) -DEFINE_CHECK_OP_IMPL(Check_LT, < ) -DEFINE_CHECK_OP_IMPL(Check_GE, >=) -DEFINE_CHECK_OP_IMPL(Check_GT, > ) -#undef DEFINE_CHECK_OP_IMPL - -// Helper macro for binary operators. -// Don't use this macro directly in your code, use CHECK_EQ et al below. - -#if defined(STATIC_ANALYSIS) -// Only for static analysis tool to know that it is equivalent to assert -#define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2)) -#elif DCHECK_IS_ON() -// In debug mode, avoid constructing CheckOpStrings if possible, -// to reduce the overhead of CHECK statments by 2x. -// Real DCHECK-heavy tests have seen 1.5x speedups. - -// The meaning of "string" might be different between now and -// when this macro gets invoked (e.g., if someone is experimenting -// with other string implementations that get defined after this -// file is included). Save the current meaning now and use it -// in the macro. -typedef std::string _Check_string; -#define CHECK_OP_LOG(name, op, val1, val2, log) \ - while (@ac_google_namespace@::_Check_string* _result = \ - @ac_google_namespace@::Check##name##Impl( \ - @ac_google_namespace@::GetReferenceableValue(val1), \ - @ac_google_namespace@::GetReferenceableValue(val2), \ - #val1 " " #op " " #val2)) \ - log(__FILE__, __LINE__, \ - @ac_google_namespace@::CheckOpString(_result)).stream() -#else -// In optimized mode, use CheckOpString to hint to compiler that -// the while condition is unlikely. -#define CHECK_OP_LOG(name, op, val1, val2, log) \ - while (@ac_google_namespace@::CheckOpString _result = \ - @ac_google_namespace@::Check##name##Impl( \ - @ac_google_namespace@::GetReferenceableValue(val1), \ - @ac_google_namespace@::GetReferenceableValue(val2), \ - #val1 " " #op " " #val2)) \ - log(__FILE__, __LINE__, _result).stream() -#endif // STATIC_ANALYSIS, DCHECK_IS_ON() - -#if GOOGLE_STRIP_LOG <= 3 -#define CHECK_OP(name, op, val1, val2) \ - CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::LogMessageFatal) -#else -#define CHECK_OP(name, op, val1, val2) \ - CHECK_OP_LOG(name, op, val1, val2, @ac_google_namespace@::NullStreamFatal) -#endif // STRIP_LOG <= 3 - -// Equality/Inequality checks - compare two values, and log a FATAL message -// including the two values when the result is not as expected. The values -// must have operator<<(ostream, ...) defined. -// -// You may append to the error message like so: -// CHECK_NE(1, 2) << ": The world must be ending!"; -// -// We are very careful to ensure that each argument is evaluated exactly -// once, and that anything which is legal to pass as a function argument is -// legal here. In particular, the arguments may be temporary expressions -// which will end up being destroyed at the end of the apparent statement, -// for example: -// CHECK_EQ(string("abc")[1], 'b'); -// -// WARNING: These don't compile correctly if one of the arguments is a pointer -// and the other is NULL. To work around this, simply static_cast NULL to the -// type of the desired pointer. - -#define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2) -#define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2) -#define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2) -#define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2) -#define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2) -#define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2) - -// Check that the input is non NULL. This very useful in constructor -// initializer lists. - -#define CHECK_NOTNULL(val) \ - @ac_google_namespace@::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val)) - -// Helper functions for string comparisons. -// To avoid bloat, the definitions are in logging.cc. -#define DECLARE_CHECK_STROP_IMPL(func, expected) \ - GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \ - const char* s1, const char* s2, const char* names); -DECLARE_CHECK_STROP_IMPL(strcmp, true) -DECLARE_CHECK_STROP_IMPL(strcmp, false) -DECLARE_CHECK_STROP_IMPL(strcasecmp, true) -DECLARE_CHECK_STROP_IMPL(strcasecmp, false) -#undef DECLARE_CHECK_STROP_IMPL - -// Helper macro for string comparisons. -// Don't use this macro directly in your code, use CHECK_STREQ et al below. -#define CHECK_STROP(func, op, expected, s1, s2) \ - while (@ac_google_namespace@::CheckOpString _result = \ - @ac_google_namespace@::Check##func##expected##Impl((s1), (s2), \ - #s1 " " #op " " #s2)) \ - LOG(FATAL) << *_result.str_ - - -// String (char*) equality/inequality checks. -// CASE versions are case-insensitive. -// -// Note that "s1" and "s2" may be temporary strings which are destroyed -// by the compiler at the end of the current "full expression" -// (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())). - -#define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2) -#define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2) -#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2) -#define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2) - -#define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0]))) -#define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0]))) - -#define CHECK_DOUBLE_EQ(val1, val2) \ - do { \ - CHECK_LE((val1), (val2)+0.000000000000001L); \ - CHECK_GE((val1), (val2)-0.000000000000001L); \ - } while (0) - -#define CHECK_NEAR(val1, val2, margin) \ - do { \ - CHECK_LE((val1), (val2)+(margin)); \ - CHECK_GE((val1), (val2)-(margin)); \ - } while (0) - -// perror()..googly style! -// -// PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and -// CHECK equivalents with the addition that they postpend a description -// of the current state of errno to their output lines. - -#define PLOG(severity) GOOGLE_PLOG(severity, 0).stream() - -#define GOOGLE_PLOG(severity, counter) \ - @ac_google_namespace@::ErrnoLogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, counter, \ - &@ac_google_namespace@::LogMessage::SendToLog) - -#define PLOG_IF(severity, condition) \ - static_cast(0), \ - !(condition) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & PLOG(severity) - -// A CHECK() macro that postpends errno if the condition is false. E.g. -// -// if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... } -#define PCHECK(condition) \ - PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \ - << "Check failed: " #condition " " - -// A CHECK() macro that lets you assert the success of a function that -// returns -1 and sets errno in case of an error. E.g. -// -// CHECK_ERR(mkdir(path, 0700)); -// -// or -// -// int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename; -#define CHECK_ERR(invocation) \ -PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \ - << #invocation - -// Use macro expansion to create, for each use of LOG_EVERY_N(), static -// variables with the __LINE__ expansion as part of the variable name. -#define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line) -#define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line - -#define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__) -#define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__) - -#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \ - static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ - ++LOG_OCCURRENCES; \ - if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ - if (LOG_OCCURRENCES_MOD_N == 1) \ - @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ - &what_to_do).stream() - -#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \ - static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ - ++LOG_OCCURRENCES; \ - if (condition && \ - ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \ - @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ - &what_to_do).stream() - -#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \ - static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ - ++LOG_OCCURRENCES; \ - if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ - if (LOG_OCCURRENCES_MOD_N == 1) \ - @ac_google_namespace@::ErrnoLogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ - &what_to_do).stream() - -#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \ - static int LOG_OCCURRENCES = 0; \ - if (LOG_OCCURRENCES <= n) \ - ++LOG_OCCURRENCES; \ - if (LOG_OCCURRENCES <= n) \ - @ac_google_namespace@::LogMessage( \ - __FILE__, __LINE__, @ac_google_namespace@::GLOG_ ## severity, LOG_OCCURRENCES, \ - &what_to_do).stream() - -namespace glog_internal_namespace_ { -template -struct CompileAssert { -}; -struct CrashReason; - -// Returns true if FailureSignalHandler is installed. -// Needs to be exported since it's used by the signalhandler_unittest. -GOOGLE_GLOG_DLL_DECL bool IsFailureSignalHandlerInstalled(); -} // namespace glog_internal_namespace_ - -#define LOG_EVERY_N(severity, n) \ - SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog) - -#define SYSLOG_EVERY_N(severity, n) \ - SOME_KIND_OF_LOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToSyslogAndLog) - -#define PLOG_EVERY_N(severity, n) \ - SOME_KIND_OF_PLOG_EVERY_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog) - -#define LOG_FIRST_N(severity, n) \ - SOME_KIND_OF_LOG_FIRST_N(severity, (n), @ac_google_namespace@::LogMessage::SendToLog) - -#define LOG_IF_EVERY_N(severity, condition, n) \ - SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), @ac_google_namespace@::LogMessage::SendToLog) - -// We want the special COUNTER value available for LOG_EVERY_X()'ed messages -enum PRIVATE_Counter {COUNTER}; - -#ifdef GLOG_NO_ABBREVIATED_SEVERITIES -// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets -// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us -// to keep using this syntax, we define this macro to do the same thing -// as COMPACT_GOOGLE_LOG_ERROR. -#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR -#define SYSLOG_0 SYSLOG_ERROR -#define LOG_TO_STRING_0 LOG_TO_STRING_ERROR -// Needed for LOG_IS_ON(ERROR). -const LogSeverity GLOG_0 = GLOG_ERROR; -#else -// Users may include windows.h after logging.h without -// GLOG_NO_ABBREVIATED_SEVERITIES nor WIN32_LEAN_AND_MEAN. -// For this case, we cannot detect if ERROR is defined before users -// actually use ERROR. Let's make an undefined symbol to warn users. -# define GLOG_ERROR_MSG ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail -# define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG -# define SYSLOG_0 GLOG_ERROR_MSG -# define LOG_TO_STRING_0 GLOG_ERROR_MSG -# define GLOG_0 GLOG_ERROR_MSG -#endif - -// Plus some debug-logging macros that get compiled to nothing for production - -#if DCHECK_IS_ON() - -#define DLOG(severity) LOG(severity) -#define DVLOG(verboselevel) VLOG(verboselevel) -#define DLOG_IF(severity, condition) LOG_IF(severity, condition) -#define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n) -#define DLOG_IF_EVERY_N(severity, condition, n) \ - LOG_IF_EVERY_N(severity, condition, n) -#define DLOG_ASSERT(condition) LOG_ASSERT(condition) - -// debug-only checking. executed if DCHECK_IS_ON(). -#define DCHECK(condition) CHECK(condition) -#define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2) -#define DCHECK_NE(val1, val2) CHECK_NE(val1, val2) -#define DCHECK_LE(val1, val2) CHECK_LE(val1, val2) -#define DCHECK_LT(val1, val2) CHECK_LT(val1, val2) -#define DCHECK_GE(val1, val2) CHECK_GE(val1, val2) -#define DCHECK_GT(val1, val2) CHECK_GT(val1, val2) -#define DCHECK_NOTNULL(val) CHECK_NOTNULL(val) -#define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2) -#define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2) -#define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2) -#define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2) - -#else // !DCHECK_IS_ON() - -#define DLOG(severity) \ - static_cast(0), \ - true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) - -#define DVLOG(verboselevel) \ - static_cast(0), \ - (true || !VLOG_IS_ON(verboselevel)) ? \ - (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(INFO) - -#define DLOG_IF(severity, condition) \ - static_cast(0), \ - (true || !(condition)) ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) - -#define DLOG_EVERY_N(severity, n) \ - static_cast(0), \ - true ? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) - -#define DLOG_IF_EVERY_N(severity, condition, n) \ - static_cast(0), \ - (true || !(condition))? (void) 0 : @ac_google_namespace@::LogMessageVoidify() & LOG(severity) - -#define DLOG_ASSERT(condition) \ - static_cast(0), \ - true ? (void) 0 : LOG_ASSERT(condition) - -// MSVC warning C4127: conditional expression is constant -#define DCHECK(condition) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK(condition) - -#define DCHECK_EQ(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2) - -#define DCHECK_NE(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2) - -#define DCHECK_LE(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2) - -#define DCHECK_LT(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2) - -#define DCHECK_GE(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2) - -#define DCHECK_GT(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2) - -// You may see warnings in release mode if you don't use the return -// value of DCHECK_NOTNULL. Please just use DCHECK for such cases. -#define DCHECK_NOTNULL(val) (val) - -#define DCHECK_STREQ(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2) - -#define DCHECK_STRCASEEQ(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2) - -#define DCHECK_STRNE(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2) - -#define DCHECK_STRCASENE(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2) - -#endif // DCHECK_IS_ON() - -// Log only in verbose mode. - -#define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel)) - -#define VLOG_IF(verboselevel, condition) \ - LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel)) - -#define VLOG_EVERY_N(verboselevel, n) \ - LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n) - -#define VLOG_IF_EVERY_N(verboselevel, condition, n) \ - LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n) - -namespace base_logging { - -// LogMessage::LogStream is a std::ostream backed by this streambuf. -// This class ignores overflow and leaves two bytes at the end of the -// buffer to allow for a '\n' and '\0'. -class GOOGLE_GLOG_DLL_DECL LogStreamBuf : public std::streambuf { - public: - // REQUIREMENTS: "len" must be >= 2 to account for the '\n' and '\0'. - LogStreamBuf(char *buf, int len) { - setp(buf, buf + len - 2); - } - - // This effectively ignores overflow. - virtual int_type overflow(int_type ch) { - return ch; - } - - // Legacy public ostrstream method. - size_t pcount() const { return pptr() - pbase(); } - char* pbase() const { return std::streambuf::pbase(); } -}; - -} // namespace base_logging - -// -// This class more or less represents a particular log message. You -// create an instance of LogMessage and then stream stuff to it. -// When you finish streaming to it, ~LogMessage is called and the -// full message gets streamed to the appropriate destination. -// -// You shouldn't actually use LogMessage's constructor to log things, -// though. You should use the LOG() macro (and variants thereof) -// above. -class GOOGLE_GLOG_DLL_DECL LogMessage { -public: - enum { - // Passing kNoLogPrefix for the line number disables the - // log-message prefix. Useful for using the LogMessage - // infrastructure as a printing utility. See also the --log_prefix - // flag for controlling the log-message prefix on an - // application-wide basis. - kNoLogPrefix = -1 - }; - - // LogStream inherit from non-DLL-exported class (std::ostrstream) - // and VC++ produces a warning for this situation. - // However, MSDN says "C4275 can be ignored in Microsoft Visual C++ - // 2005 if you are deriving from a type in the Standard C++ Library" - // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx - // Let's just ignore the warning. -GLOG_MSVC_PUSH_DISABLE_WARNING(4275) - class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostream { -GLOG_MSVC_POP_WARNING() - public: - LogStream(char *buf, int len, int ctr) - : std::ostream(NULL), - streambuf_(buf, len), - ctr_(ctr), - self_(this) { - rdbuf(&streambuf_); - } - - int ctr() const { return ctr_; } - void set_ctr(int ctr) { ctr_ = ctr; } - LogStream* self() const { return self_; } - - // Legacy std::streambuf methods. - size_t pcount() const { return streambuf_.pcount(); } - char* pbase() const { return streambuf_.pbase(); } - char* str() const { return pbase(); } - - private: - LogStream(const LogStream&); - LogStream& operator=(const LogStream&); - base_logging::LogStreamBuf streambuf_; - int ctr_; // Counter hack (for the LOG_EVERY_X() macro) - LogStream *self_; // Consistency check hack - }; - -public: - // icc 8 requires this typedef to avoid an internal compiler error. - typedef void (LogMessage::*SendMethod)(); - - LogMessage(const char* file, int line, LogSeverity severity, int ctr, - SendMethod send_method); - - // Two special constructors that generate reduced amounts of code at - // LOG call sites for common cases. - - // Used for LOG(INFO): Implied are: - // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog. - // - // Using this constructor instead of the more complex constructor above - // saves 19 bytes per call site. - LogMessage(const char* file, int line); - - // Used for LOG(severity) where severity != INFO. Implied - // are: ctr = 0, send_method = &LogMessage::SendToLog - // - // Using this constructor instead of the more complex constructor above - // saves 17 bytes per call site. - LogMessage(const char* file, int line, LogSeverity severity); - - // Constructor to log this message to a specified sink (if not NULL). - // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if - // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise. - LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink, - bool also_send_to_log); - - // Constructor where we also give a vector pointer - // for storing the messages (if the pointer is not NULL). - // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog. - LogMessage(const char* file, int line, LogSeverity severity, - std::vector* outvec); - - // Constructor where we also give a string pointer for storing the - // message (if the pointer is not NULL). Implied are: ctr = 0, - // send_method = &LogMessage::WriteToStringAndLog. - LogMessage(const char* file, int line, LogSeverity severity, - std::string* message); - - // A special constructor used for check failures - LogMessage(const char* file, int line, const CheckOpString& result); - - ~LogMessage(); - - // Flush a buffered message to the sink set in the constructor. Always - // called by the destructor, it may also be called from elsewhere if - // needed. Only the first call is actioned; any later ones are ignored. - void Flush(); - - // An arbitrary limit on the length of a single log message. This - // is so that streaming can be done more efficiently. - static const size_t kMaxLogMessageLen; - - // Theses should not be called directly outside of logging.*, - // only passed as SendMethod arguments to other LogMessage methods: - void SendToLog(); // Actually dispatch to the logs - void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs - - // Call abort() or similar to perform LOG(FATAL) crash. - static void @ac_cv___attribute___noreturn@ Fail(); - - std::ostream& stream(); - - int preserved_errno() const; - - // Must be called without the log_mutex held. (L < log_mutex) - static int64 num_messages(int severity); - - struct LogMessageData; - -private: - // Fully internal SendMethod cases: - void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs - void SendToSink(); // Send to sink if provided, do nothing otherwise. - - // Write to string if provided and dispatch to the logs. - void WriteToStringAndLog(); - - void SaveOrSendToLog(); // Save to stringvec if provided, else to logs - - void Init(const char* file, int line, LogSeverity severity, - void (LogMessage::*send_method)()); - - // Used to fill in crash information during LOG(FATAL) failures. - void RecordCrashReason(glog_internal_namespace_::CrashReason* reason); - - // Counts of messages sent at each priority: - static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex - - // We keep the data in a separate struct so that each instance of - // LogMessage uses less stack space. - LogMessageData* allocated_; - LogMessageData* data_; - - friend class LogDestination; - - LogMessage(const LogMessage&); - void operator=(const LogMessage&); -}; - -// This class happens to be thread-hostile because all instances share -// a single data buffer, but since it can only be created just before -// the process dies, we don't worry so much. -class GOOGLE_GLOG_DLL_DECL LogMessageFatal : public LogMessage { - public: - LogMessageFatal(const char* file, int line); - LogMessageFatal(const char* file, int line, const CheckOpString& result); - @ac_cv___attribute___noreturn@ ~LogMessageFatal(); -}; - -// A non-macro interface to the log facility; (useful -// when the logging level is not a compile-time constant). -inline void LogAtLevel(int const severity, std::string const &msg) { - LogMessage(__FILE__, __LINE__, severity).stream() << msg; -} - -// A macro alternative of LogAtLevel. New code may want to use this -// version since there are two advantages: 1. this version outputs the -// file name and the line number where this macro is put like other -// LOG macros, 2. this macro can be used as C++ stream. -#define LOG_AT_LEVEL(severity) @ac_google_namespace@::LogMessage(__FILE__, __LINE__, severity).stream() - -// Check if it's compiled in C++11 mode. -// -// GXX_EXPERIMENTAL_CXX0X is defined by gcc and clang up to at least -// gcc-4.7 and clang-3.1 (2011-12-13). __cplusplus was defined to 1 -// in gcc before 4.7 (Crosstool 16) and clang before 3.1, but is -// defined according to the language version in effect thereafter. -// Microsoft Visual Studio 14 (2015) sets __cplusplus==199711 despite -// reasonably good C++11 support, so we set LANG_CXX for it and -// newer versions (_MSC_VER >= 1900). -#if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L || \ - (defined(_MSC_VER) && _MSC_VER >= 1900)) -// Helper for CHECK_NOTNULL(). -// -// In C++11, all cases can be handled by a single function. Since the value -// category of the argument is preserved (also for rvalue references), -// member initializer lists like the one below will compile correctly: -// -// Foo() -// : x_(CHECK_NOTNULL(MethodReturningUniquePtr())) {} -template -T CheckNotNull(const char* file, int line, const char* names, T&& t) { - if (t == nullptr) { - LogMessageFatal(file, line, new std::string(names)); - } - return std::forward(t); -} - -#else - -// A small helper for CHECK_NOTNULL(). -template -T* CheckNotNull(const char *file, int line, const char *names, T* t) { - if (t == NULL) { - LogMessageFatal(file, line, new std::string(names)); - } - return t; -} -#endif - -// Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This -// only works if ostream is a LogStream. If the ostream is not a -// LogStream you'll get an assert saying as much at runtime. -GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream &os, - const PRIVATE_Counter&); - - -// Derived class for PLOG*() above. -class GOOGLE_GLOG_DLL_DECL ErrnoLogMessage : public LogMessage { - public: - - ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr, - void (LogMessage::*send_method)()); - - // Postpends ": strerror(errno) [errno]". - ~ErrnoLogMessage(); - - private: - ErrnoLogMessage(const ErrnoLogMessage&); - void operator=(const ErrnoLogMessage&); -}; - - -// This class is used to explicitly ignore values in the conditional -// logging macros. This avoids compiler warnings like "value computed -// is not used" and "statement has no effect". - -class GOOGLE_GLOG_DLL_DECL LogMessageVoidify { - public: - LogMessageVoidify() { } - // This has to be an operator with a precedence lower than << but - // higher than ?: - void operator&(std::ostream&) { } -}; - - -// Flushes all log files that contains messages that are at least of -// the specified severity level. Thread-safe. -GOOGLE_GLOG_DLL_DECL void FlushLogFiles(LogSeverity min_severity); - -// Flushes all log files that contains messages that are at least of -// the specified severity level. Thread-hostile because it ignores -// locking -- used for catastrophic failures. -GOOGLE_GLOG_DLL_DECL void FlushLogFilesUnsafe(LogSeverity min_severity); - -// -// Set the destination to which a particular severity level of log -// messages is sent. If base_filename is "", it means "don't log this -// severity". Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetLogDestination(LogSeverity severity, - const char* base_filename); - -// -// Set the basename of the symlink to the latest log file at a given -// severity. If symlink_basename is empty, do not make a symlink. If -// you don't call this function, the symlink basename is the -// invocation name of the program. Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetLogSymlink(LogSeverity severity, - const char* symlink_basename); - -// -// Used to send logs to some other kind of destination -// Users should subclass LogSink and override send to do whatever they want. -// Implementations must be thread-safe because a shared instance will -// be called from whichever thread ran the LOG(XXX) line. -class GOOGLE_GLOG_DLL_DECL LogSink { - public: - virtual ~LogSink(); - - // Sink's logging logic (message_len is such as to exclude '\n' at the end). - // This method can't use LOG() or CHECK() as logging system mutex(s) are held - // during this call. - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, - const struct ::tm* tm_time, - const char* message, size_t message_len) = 0; - - // Redefine this to implement waiting for - // the sink's logging logic to complete. - // It will be called after each send() returns, - // but before that LogMessage exits or crashes. - // By default this function does nothing. - // Using this function one can implement complex logic for send() - // that itself involves logging; and do all this w/o causing deadlocks and - // inconsistent rearrangement of log messages. - // E.g. if a LogSink has thread-specific actions, the send() method - // can simply add the message to a queue and wake up another thread that - // handles real logging while itself making some LOG() calls; - // WaitTillSent() can be implemented to wait for that logic to complete. - // See our unittest for an example. - virtual void WaitTillSent(); - - // Returns the normal text output of the log message. - // Can be useful to implement send(). - static std::string ToString(LogSeverity severity, const char* file, int line, - const struct ::tm* tm_time, - const char* message, size_t message_len); -}; - -// Add or remove a LogSink as a consumer of logging data. Thread-safe. -GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink *destination); -GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink *destination); - -// -// Specify an "extension" added to the filename specified via -// SetLogDestination. This applies to all severity levels. It's -// often used to append the port we're listening on to the logfile -// name. Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetLogFilenameExtension( - const char* filename_extension); - -// -// Make it so that all log messages of at least a particular severity -// are logged to stderr (in addition to logging to the usual log -// file(s)). Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetStderrLogging(LogSeverity min_severity); - -// -// Make it so that all log messages go only to stderr. Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void LogToStderr(); - -// -// Make it so that all log messages of at least a particular severity are -// logged via email to a list of addresses (in addition to logging to the -// usual log file(s)). The list of addresses is just a string containing -// the email addresses to send to (separated by spaces, say). Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetEmailLogging(LogSeverity min_severity, - const char* addresses); - -// A simple function that sends email. dest is a commma-separated -// list of addressess. Thread-safe. -GOOGLE_GLOG_DLL_DECL bool SendEmail(const char *dest, - const char *subject, const char *body); - -GOOGLE_GLOG_DLL_DECL const std::vector& GetLoggingDirectories(); - -// For tests only: Clear the internal [cached] list of logging directories to -// force a refresh the next time GetLoggingDirectories is called. -// Thread-hostile. -void TestOnly_ClearLoggingDirectoriesList(); - -// Returns a set of existing temporary directories, which will be a -// subset of the directories returned by GetLogginDirectories(). -// Thread-safe. -GOOGLE_GLOG_DLL_DECL void GetExistingTempDirectories( - std::vector* list); - -// Print any fatal message again -- useful to call from signal handler -// so that the last thing in the output is the fatal message. -// Thread-hostile, but a race is unlikely. -GOOGLE_GLOG_DLL_DECL void ReprintFatalMessage(); - -// Truncate a log file that may be the append-only output of multiple -// processes and hence can't simply be renamed/reopened (typically a -// stdout/stderr). If the file "path" is > "limit" bytes, copy the -// last "keep" bytes to offset 0 and truncate the rest. Since we could -// be racing with other writers, this approach has the potential to -// lose very small amounts of data. For security, only follow symlinks -// if the path is /proc/self/fd/* -GOOGLE_GLOG_DLL_DECL void TruncateLogFile(const char *path, - int64 limit, int64 keep); - -// Truncate stdout and stderr if they are over the value specified by -// --max_log_size; keep the final 1MB. This function has the same -// race condition as TruncateLogFile. -GOOGLE_GLOG_DLL_DECL void TruncateStdoutStderr(); - -// Return the string representation of the provided LogSeverity level. -// Thread-safe. -GOOGLE_GLOG_DLL_DECL const char* GetLogSeverityName(LogSeverity severity); - -// --------------------------------------------------------------------- -// Implementation details that are not useful to most clients -// --------------------------------------------------------------------- - -// A Logger is the interface used by logging modules to emit entries -// to a log. A typical implementation will dump formatted data to a -// sequence of files. We also provide interfaces that will forward -// the data to another thread so that the invoker never blocks. -// Implementations should be thread-safe since the logging system -// will write to them from multiple threads. - -namespace base { - -class GOOGLE_GLOG_DLL_DECL Logger { - public: - virtual ~Logger(); - - // Writes "message[0,message_len-1]" corresponding to an event that - // occurred at "timestamp". If "force_flush" is true, the log file - // is flushed immediately. - // - // The input message has already been formatted as deemed - // appropriate by the higher level logging facility. For example, - // textual log messages already contain timestamps, and the - // file:linenumber header. - virtual void Write(bool force_flush, - time_t timestamp, - const char* message, - int message_len) = 0; - - // Flush any buffered messages - virtual void Flush() = 0; - - // Get the current LOG file size. - // The returned value is approximate since some - // logged data may not have been flushed to disk yet. - virtual uint32 LogSize() = 0; -}; - -// Get the logger for the specified severity level. The logger -// remains the property of the logging module and should not be -// deleted by the caller. Thread-safe. -extern GOOGLE_GLOG_DLL_DECL Logger* GetLogger(LogSeverity level); - -// Set the logger for the specified severity level. The logger -// becomes the property of the logging module and should not -// be deleted by the caller. Thread-safe. -extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger); - -} - -// glibc has traditionally implemented two incompatible versions of -// strerror_r(). There is a poorly defined convention for picking the -// version that we want, but it is not clear whether it even works with -// all versions of glibc. -// So, instead, we provide this wrapper that automatically detects the -// version that is in use, and then implements POSIX semantics. -// N.B. In addition to what POSIX says, we also guarantee that "buf" will -// be set to an empty string, if this function failed. This means, in most -// cases, you do not need to check the error code and you can directly -// use the value of "buf". It will never have an undefined value. -// DEPRECATED: Use StrError(int) instead. -GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char *buf, size_t len); - -// A thread-safe replacement for strerror(). Returns a string describing the -// given POSIX error code. -GOOGLE_GLOG_DLL_DECL std::string StrError(int err); - -// A class for which we define operator<<, which does nothing. -class GOOGLE_GLOG_DLL_DECL NullStream : public LogMessage::LogStream { - public: - // Initialize the LogStream so the messages can be written somewhere - // (they'll never be actually displayed). This will be needed if a - // NullStream& is implicitly converted to LogStream&, in which case - // the overloaded NullStream::operator<< will not be invoked. - NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { } - NullStream(const char* /*file*/, int /*line*/, - const CheckOpString& /*result*/) : - LogMessage::LogStream(message_buffer_, 1, 0) { } - NullStream &stream() { return *this; } - private: - // A very short buffer for messages (which we discard anyway). This - // will be needed if NullStream& converted to LogStream& (e.g. as a - // result of a conditional expression). - char message_buffer_[2]; -}; - -// Do nothing. This operator is inline, allowing the message to be -// compiled away. The message will not be compiled away if we do -// something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when -// SKIP_LOG=WARNING. In those cases, NullStream will be implicitly -// converted to LogStream and the message will be computed and then -// quietly discarded. -template -inline NullStream& operator<<(NullStream &str, const T &) { return str; } - -// Similar to NullStream, but aborts the program (without stack -// trace), like LogMessageFatal. -class GOOGLE_GLOG_DLL_DECL NullStreamFatal : public NullStream { - public: - NullStreamFatal() { } - NullStreamFatal(const char* file, int line, const CheckOpString& result) : - NullStream(file, line, result) { } - @ac_cv___attribute___noreturn@ ~NullStreamFatal() throw () { _exit(1); } -}; - -// Install a signal handler that will dump signal information and a stack -// trace when the program crashes on certain signals. We'll install the -// signal handler for the following signals. -// -// SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM. -// -// By default, the signal handler will write the failure dump to the -// standard error. You can customize the destination by installing your -// own writer function by InstallFailureWriter() below. -// -// Note on threading: -// -// The function should be called before threads are created, if you want -// to use the failure signal handler for all threads. The stack trace -// will be shown only for the thread that receives the signal. In other -// words, stack traces of other threads won't be shown. -GOOGLE_GLOG_DLL_DECL void InstallFailureSignalHandler(); - -// Installs a function that is used for writing the failure dump. "data" -// is the pointer to the beginning of a message to be written, and "size" -// is the size of the message. You should not expect the data is -// terminated with '\0'. -GOOGLE_GLOG_DLL_DECL void InstallFailureWriter( - void (*writer)(const char* data, int size)); - -@ac_google_end_namespace@ - -#endif // _LOGGING_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/raw_logging.h.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/raw_logging.h.in deleted file mode 100644 index 3eac56a3bd1..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/raw_logging.h.in +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Maxim Lifantsev -// -// Thread-safe logging routines that do not allocate any memory or -// acquire any locks, and can therefore be used by low-level memory -// allocation and synchronization code. - -#ifndef BASE_RAW_LOGGING_H_ -#define BASE_RAW_LOGGING_H_ - -#include - -@ac_google_start_namespace@ - -#include "glog/log_severity.h" -#include "glog/vlog_is_on.h" - -// Annoying stuff for windows -- makes sure clients can import these functions -#ifndef GOOGLE_GLOG_DLL_DECL -# if defined(_WIN32) && !defined(__CYGWIN__) -# define GOOGLE_GLOG_DLL_DECL __declspec(dllimport) -# else -# define GOOGLE_GLOG_DLL_DECL -# endif -#endif - -// This is similar to LOG(severity) << format... and VLOG(level) << format.., -// but -// * it is to be used ONLY by low-level modules that can't use normal LOG() -// * it is desiged to be a low-level logger that does not allocate any -// memory and does not need any locks, hence: -// * it logs straight and ONLY to STDERR w/o buffering -// * it uses an explicit format and arguments list -// * it will silently chop off really long message strings -// Usage example: -// RAW_LOG(ERROR, "Failed foo with %i: %s", status, error); -// RAW_VLOG(3, "status is %i", status); -// These will print an almost standard log lines like this to stderr only: -// E0821 211317 file.cc:123] RAW: Failed foo with 22: bad_file -// I0821 211317 file.cc:142] RAW: status is 20 -#define RAW_LOG(severity, ...) \ - do { \ - switch (@ac_google_namespace@::GLOG_ ## severity) { \ - case 0: \ - RAW_LOG_INFO(__VA_ARGS__); \ - break; \ - case 1: \ - RAW_LOG_WARNING(__VA_ARGS__); \ - break; \ - case 2: \ - RAW_LOG_ERROR(__VA_ARGS__); \ - break; \ - case 3: \ - RAW_LOG_FATAL(__VA_ARGS__); \ - break; \ - default: \ - break; \ - } \ - } while (0) - -// The following STRIP_LOG testing is performed in the header file so that it's -// possible to completely compile out the logging code and the log messages. -#if STRIP_LOG == 0 -#define RAW_VLOG(verboselevel, ...) \ - do { \ - if (VLOG_IS_ON(verboselevel)) { \ - RAW_LOG_INFO(__VA_ARGS__); \ - } \ - } while (0) -#else -#define RAW_VLOG(verboselevel, ...) RawLogStub__(0, __VA_ARGS__) -#endif // STRIP_LOG == 0 - -#if STRIP_LOG == 0 -#define RAW_LOG_INFO(...) @ac_google_namespace@::RawLog__(@ac_google_namespace@::GLOG_INFO, \ - __FILE__, __LINE__, __VA_ARGS__) -#else -#define RAW_LOG_INFO(...) @ac_google_namespace@::RawLogStub__(0, __VA_ARGS__) -#endif // STRIP_LOG == 0 - -#if STRIP_LOG <= 1 -#define RAW_LOG_WARNING(...) @ac_google_namespace@::RawLog__(@ac_google_namespace@::GLOG_WARNING, \ - __FILE__, __LINE__, __VA_ARGS__) -#else -#define RAW_LOG_WARNING(...) @ac_google_namespace@::RawLogStub__(0, __VA_ARGS__) -#endif // STRIP_LOG <= 1 - -#if STRIP_LOG <= 2 -#define RAW_LOG_ERROR(...) @ac_google_namespace@::RawLog__(@ac_google_namespace@::GLOG_ERROR, \ - __FILE__, __LINE__, __VA_ARGS__) -#else -#define RAW_LOG_ERROR(...) @ac_google_namespace@::RawLogStub__(0, __VA_ARGS__) -#endif // STRIP_LOG <= 2 - -#if STRIP_LOG <= 3 -#define RAW_LOG_FATAL(...) @ac_google_namespace@::RawLog__(@ac_google_namespace@::GLOG_FATAL, \ - __FILE__, __LINE__, __VA_ARGS__) -#else -#define RAW_LOG_FATAL(...) \ - do { \ - @ac_google_namespace@::RawLogStub__(0, __VA_ARGS__); \ - exit(1); \ - } while (0) -#endif // STRIP_LOG <= 3 - -// Similar to CHECK(condition) << message, -// but for low-level modules: we use only RAW_LOG that does not allocate memory. -// We do not want to provide args list here to encourage this usage: -// if (!cond) RAW_LOG(FATAL, "foo ...", hard_to_compute_args); -// so that the args are not computed when not needed. -#define RAW_CHECK(condition, message) \ - do { \ - if (!(condition)) { \ - RAW_LOG(FATAL, "Check %s failed: %s", #condition, message); \ - } \ - } while (0) - -// Debug versions of RAW_LOG and RAW_CHECK -#ifndef NDEBUG - -#define RAW_DLOG(severity, ...) RAW_LOG(severity, __VA_ARGS__) -#define RAW_DCHECK(condition, message) RAW_CHECK(condition, message) - -#else // NDEBUG - -#define RAW_DLOG(severity, ...) \ - while (false) \ - RAW_LOG(severity, __VA_ARGS__) -#define RAW_DCHECK(condition, message) \ - while (false) \ - RAW_CHECK(condition, message) - -#endif // NDEBUG - -// Stub log function used to work around for unused variable warnings when -// building with STRIP_LOG > 0. -static inline void RawLogStub__(int /* ignored */, ...) { -} - -// Helper function to implement RAW_LOG and RAW_VLOG -// Logs format... at "severity" level, reporting it -// as called from file:line. -// This does not allocate memory or acquire locks. -GOOGLE_GLOG_DLL_DECL void RawLog__(LogSeverity severity, - const char* file, - int line, - const char* format, ...) - @ac_cv___attribute___printf_4_5@; - -@ac_google_end_namespace@ - -#endif // BASE_RAW_LOGGING_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/stl_logging.h.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/stl_logging.h.in deleted file mode 100644 index 600945d2c22..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/stl_logging.h.in +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright (c) 2003, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Stream output operators for STL containers; to be used for logging *only*. -// Inclusion of this file lets you do: -// -// list x; -// LOG(INFO) << "data: " << x; -// vector v1, v2; -// CHECK_EQ(v1, v2); -// -// If you want to use this header file with hash maps or slist, you -// need to define macros before including this file: -// -// - GLOG_STL_LOGGING_FOR_UNORDERED - and -// - GLOG_STL_LOGGING_FOR_TR1_UNORDERED - -// - GLOG_STL_LOGGING_FOR_EXT_HASH - -// - GLOG_STL_LOGGING_FOR_EXT_SLIST - -// - -#ifndef UTIL_GTL_STL_LOGGING_INL_H_ -#define UTIL_GTL_STL_LOGGING_INL_H_ - -#if !@ac_cv_cxx_using_operator@ -# error We do not support stl_logging for this compiler -#endif - -#include -#include -#include -#include -#include -#include -#include - -#ifdef GLOG_STL_LOGGING_FOR_UNORDERED -# include -# include -#endif - -#ifdef GLOG_STL_LOGGING_FOR_TR1_UNORDERED -# include -# include -#endif - -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH -# include -# include -#endif -#ifdef GLOG_STL_LOGGING_FOR_EXT_SLIST -# include -#endif - -// Forward declare these two, and define them after all the container streams -// operators so that we can recurse from pair -> container -> container -> pair -// properly. -template -std::ostream& operator<<(std::ostream& out, const std::pair& p); - -@ac_google_start_namespace@ - -template -void PrintSequence(std::ostream& out, Iter begin, Iter end); - -@ac_google_end_namespace@ - -#define OUTPUT_TWO_ARG_CONTAINER(Sequence) \ -template \ -inline std::ostream& operator<<(std::ostream& out, \ - const Sequence& seq) { \ - @ac_google_namespace@::PrintSequence(out, seq.begin(), seq.end()); \ - return out; \ -} - -OUTPUT_TWO_ARG_CONTAINER(std::vector) -OUTPUT_TWO_ARG_CONTAINER(std::deque) -OUTPUT_TWO_ARG_CONTAINER(std::list) -#ifdef GLOG_STL_LOGGING_FOR_EXT_SLIST -OUTPUT_TWO_ARG_CONTAINER(__gnu_cxx::slist) -#endif - -#undef OUTPUT_TWO_ARG_CONTAINER - -#define OUTPUT_THREE_ARG_CONTAINER(Sequence) \ -template \ -inline std::ostream& operator<<(std::ostream& out, \ - const Sequence& seq) { \ - @ac_google_namespace@::PrintSequence(out, seq.begin(), seq.end()); \ - return out; \ -} - -OUTPUT_THREE_ARG_CONTAINER(std::set) -OUTPUT_THREE_ARG_CONTAINER(std::multiset) - -#undef OUTPUT_THREE_ARG_CONTAINER - -#define OUTPUT_FOUR_ARG_CONTAINER(Sequence) \ -template \ -inline std::ostream& operator<<(std::ostream& out, \ - const Sequence& seq) { \ - @ac_google_namespace@::PrintSequence(out, seq.begin(), seq.end()); \ - return out; \ -} - -OUTPUT_FOUR_ARG_CONTAINER(std::map) -OUTPUT_FOUR_ARG_CONTAINER(std::multimap) -#ifdef GLOG_STL_LOGGING_FOR_UNORDERED -OUTPUT_FOUR_ARG_CONTAINER(std::unordered_set) -OUTPUT_FOUR_ARG_CONTAINER(std::unordered_multiset) -#endif -#ifdef GLOG_STL_LOGGING_FOR_TR1_UNORDERED -OUTPUT_FOUR_ARG_CONTAINER(std::tr1::unordered_set) -OUTPUT_FOUR_ARG_CONTAINER(std::tr1::unordered_multiset) -#endif -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH -OUTPUT_FOUR_ARG_CONTAINER(__gnu_cxx::hash_set) -OUTPUT_FOUR_ARG_CONTAINER(__gnu_cxx::hash_multiset) -#endif - -#undef OUTPUT_FOUR_ARG_CONTAINER - -#define OUTPUT_FIVE_ARG_CONTAINER(Sequence) \ -template \ -inline std::ostream& operator<<(std::ostream& out, \ - const Sequence& seq) { \ - @ac_google_namespace@::PrintSequence(out, seq.begin(), seq.end()); \ - return out; \ -} - -#ifdef GLOG_STL_LOGGING_FOR_UNORDERED -OUTPUT_FIVE_ARG_CONTAINER(std::unordered_map) -OUTPUT_FIVE_ARG_CONTAINER(std::unordered_multimap) -#endif -#ifdef GLOG_STL_LOGGING_FOR_TR1_UNORDERED -OUTPUT_FIVE_ARG_CONTAINER(std::tr1::unordered_map) -OUTPUT_FIVE_ARG_CONTAINER(std::tr1::unordered_multimap) -#endif -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH -OUTPUT_FIVE_ARG_CONTAINER(__gnu_cxx::hash_map) -OUTPUT_FIVE_ARG_CONTAINER(__gnu_cxx::hash_multimap) -#endif - -#undef OUTPUT_FIVE_ARG_CONTAINER - -template -inline std::ostream& operator<<(std::ostream& out, - const std::pair& p) { - out << '(' << p.first << ", " << p.second << ')'; - return out; -} - -@ac_google_start_namespace@ - -template -inline void PrintSequence(std::ostream& out, Iter begin, Iter end) { - // Output at most 100 elements -- appropriate if used for logging. - for (int i = 0; begin != end && i < 100; ++i, ++begin) { - if (i > 0) out << ' '; - out << *begin; - } - if (begin != end) { - out << " ..."; - } -} - -@ac_google_end_namespace@ - -// Note that this is technically undefined behavior! We are adding things into -// the std namespace for a reason though -- we are providing new operations on -// types which are themselves defined with this namespace. Without this, these -// operator overloads cannot be found via ADL. If these definitions are not -// found via ADL, they must be #included before they're used, which requires -// this header to be included before apparently independent other headers. -// -// For example, base/logging.h defines various template functions to implement -// CHECK_EQ(x, y) and stream x and y into the log in the event the check fails. -// It does so via the function template MakeCheckOpValueString: -// template -// void MakeCheckOpValueString(strstream* ss, const T& v) { -// (*ss) << v; -// } -// Because 'glog/logging.h' is included before 'glog/stl_logging.h', -// subsequent CHECK_EQ(v1, v2) for vector<...> typed variable v1 and v2 can only -// find these operator definitions via ADL. -// -// Even this solution has problems -- it may pull unintended operators into the -// namespace as well, allowing them to also be found via ADL, and creating code -// that only works with a particular order of includes. Long term, we need to -// move all of the *definitions* into namespace std, bet we need to ensure no -// one references them first. This lets us take that step. We cannot define them -// in both because that would create ambiguous overloads when both are found. -namespace std { using ::operator<<; } - -#endif // UTIL_GTL_STL_LOGGING_INL_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/vlog_is_on.h.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/vlog_is_on.h.in deleted file mode 100644 index 3f4c4a32a8b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/glog/vlog_is_on.h.in +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) 1999, 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Ray Sidney and many others -// -// Defines the VLOG_IS_ON macro that controls the variable-verbosity -// conditional logging. -// -// It's used by VLOG and VLOG_IF in logging.h -// and by RAW_VLOG in raw_logging.h to trigger the logging. -// -// It can also be used directly e.g. like this: -// if (VLOG_IS_ON(2)) { -// // do some logging preparation and logging -// // that can't be accomplished e.g. via just VLOG(2) << ...; -// } -// -// The truth value that VLOG_IS_ON(level) returns is determined by -// the three verbosity level flags: -// --v= Gives the default maximal active V-logging level; -// 0 is the default. -// Normally positive values are used for V-logging levels. -// --vmodule= Gives the per-module maximal V-logging levels to override -// the value given by --v. -// E.g. "my_module=2,foo*=3" would change the logging level -// for all code in source files "my_module.*" and "foo*.*" -// ("-inl" suffixes are also disregarded for this matching). -// -// SetVLOGLevel helper function is provided to do limited dynamic control over -// V-logging by overriding the per-module settings given via --vmodule flag. -// -// CAVEAT: --vmodule functionality is not available in non gcc compilers. -// - -#ifndef BASE_VLOG_IS_ON_H_ -#define BASE_VLOG_IS_ON_H_ - -#include "glog/log_severity.h" - -// Annoying stuff for windows -- makes sure clients can import these functions -#ifndef GOOGLE_GLOG_DLL_DECL -# if defined(_WIN32) && !defined(__CYGWIN__) -# define GOOGLE_GLOG_DLL_DECL __declspec(dllimport) -# else -# define GOOGLE_GLOG_DLL_DECL -# endif -#endif - -#if defined(__GNUC__) -// We emit an anonymous static int* variable at every VLOG_IS_ON(n) site. -// (Normally) the first time every VLOG_IS_ON(n) site is hit, -// we determine what variable will dynamically control logging at this site: -// it's either FLAGS_v or an appropriate internal variable -// matching the current source file that represents results of -// parsing of --vmodule flag and/or SetVLOGLevel calls. -#define VLOG_IS_ON(verboselevel) \ - __extension__ \ - ({ static @ac_google_namespace@::int32* vlocal__ = &@ac_google_namespace@::kLogSiteUninitialized; \ - @ac_google_namespace@::int32 verbose_level__ = (verboselevel); \ - (*vlocal__ >= verbose_level__) && \ - ((vlocal__ != &@ac_google_namespace@::kLogSiteUninitialized) || \ - (@ac_google_namespace@::InitVLOG3__(&vlocal__, &FLAGS_v, \ - __FILE__, verbose_level__))); }) -#else -// GNU extensions not available, so we do not support --vmodule. -// Dynamic value of FLAGS_v always controls the logging level. -#define VLOG_IS_ON(verboselevel) (FLAGS_v >= (verboselevel)) -#endif - -// Set VLOG(_IS_ON) level for module_pattern to log_level. -// This lets us dynamically control what is normally set by the --vmodule flag. -// Returns the level that previously applied to module_pattern. -// NOTE: To change the log level for VLOG(_IS_ON) sites -// that have already executed after/during InitGoogleLogging, -// one needs to supply the exact --vmodule pattern that applied to them. -// (If no --vmodule pattern applied to them -// the value of FLAGS_v will continue to control them.) -extern GOOGLE_GLOG_DLL_DECL int SetVLOGLevel(const char* module_pattern, - int log_level); - -// Various declarations needed for VLOG_IS_ON above: ========================= - -// Special value used to indicate that a VLOG_IS_ON site has not been -// initialized. We make this a large value, so the common-case check -// of "*vlocal__ >= verbose_level__" in VLOG_IS_ON definition -// passes in such cases and InitVLOG3__ is then triggered. -extern @ac_google_namespace@::int32 kLogSiteUninitialized; - -// Helper routine which determines the logging info for a particalur VLOG site. -// site_flag is the address of the site-local pointer to the controlling -// verbosity level -// site_default is the default to use for *site_flag -// fname is the current source file name -// verbose_level is the argument to VLOG_IS_ON -// We will return the return value for VLOG_IS_ON -// and if possible set *site_flag appropriately. -extern GOOGLE_GLOG_DLL_DECL bool InitVLOG3__( - @ac_google_namespace@::int32** site_flag, - @ac_google_namespace@::int32* site_default, - const char* fname, - @ac_google_namespace@::int32 verbose_level); - -#endif // BASE_VLOG_IS_ON_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/googletest.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/googletest.h deleted file mode 100644 index 49ddbc0a5d8..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/googletest.h +++ /dev/null @@ -1,606 +0,0 @@ -// Copyright (c) 2009, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Shinichiro Hamaji -// (based on googletest: http://code.google.com/p/googletest/) - -#ifdef GOOGLETEST_H__ -#error You must not include this file twice. -#endif -#define GOOGLETEST_H__ - -#include "utilities.h" - -#include -#include -#include - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#ifdef HAVE_UNISTD_H -# include -#endif - -#include "base/commandlineflags.h" - -using std::map; -using std::string; -using std::vector; - -_START_GOOGLE_NAMESPACE_ - -extern GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)(); - -_END_GOOGLE_NAMESPACE_ - -#undef GOOGLE_GLOG_DLL_DECL -#define GOOGLE_GLOG_DLL_DECL - -static inline string GetTempDir() { -#ifndef OS_WINDOWS - return "/tmp"; -#else - char tmp[MAX_PATH]; - GetTempPathA(MAX_PATH, tmp); - return tmp; -#endif -} - -#if defined(OS_WINDOWS) && defined(_MSC_VER) && !defined(TEST_SRC_DIR) -// The test will run in glog/vsproject/ -// (e.g., glog/vsproject/logging_unittest). -static const char TEST_SRC_DIR[] = "../.."; -#elif !defined(TEST_SRC_DIR) -# warning TEST_SRC_DIR should be defined in config.h -static const char TEST_SRC_DIR[] = "."; -#endif - -static const uint32_t PTR_TEST_VALUE = 0x12345678; - -DEFINE_string(test_tmpdir, GetTempDir(), "Dir we use for temp files"); -DEFINE_string(test_srcdir, TEST_SRC_DIR, - "Source-dir root, needed to find glog_unittest_flagfile"); -DEFINE_bool(run_benchmark, false, "If true, run benchmarks"); -#ifdef NDEBUG -DEFINE_int32(benchmark_iters, 100000000, "Number of iterations per benchmark"); -#else -DEFINE_int32(benchmark_iters, 100000, "Number of iterations per benchmark"); -#endif - -#ifdef HAVE_LIB_GTEST -# include -// Use our ASSERT_DEATH implementation. -# undef ASSERT_DEATH -# undef ASSERT_DEBUG_DEATH -using testing::InitGoogleTest; -#else - -_START_GOOGLE_NAMESPACE_ - -void InitGoogleTest(int*, char**); - -void InitGoogleTest(int*, char**) {} - -// The following is some bare-bones testing infrastructure - -#define EXPECT_TRUE(cond) \ - do { \ - if (!(cond)) { \ - fprintf(stderr, "Check failed: %s\n", #cond); \ - exit(1); \ - } \ - } while (0) - -#define EXPECT_FALSE(cond) EXPECT_TRUE(!(cond)) - -#define EXPECT_OP(op, val1, val2) \ - do { \ - if (!((val1) op (val2))) { \ - fprintf(stderr, "Check failed: %s %s %s\n", #val1, #op, #val2); \ - exit(1); \ - } \ - } while (0) - -#define EXPECT_EQ(val1, val2) EXPECT_OP(==, val1, val2) -#define EXPECT_NE(val1, val2) EXPECT_OP(!=, val1, val2) -#define EXPECT_GT(val1, val2) EXPECT_OP(>, val1, val2) -#define EXPECT_LT(val1, val2) EXPECT_OP(<, val1, val2) - -#define EXPECT_NAN(arg) \ - do { \ - if (!isnan(arg)) { \ - fprintf(stderr, "Check failed: isnan(%s)\n", #arg); \ - exit(1); \ - } \ - } while (0) - -#define EXPECT_INF(arg) \ - do { \ - if (!isinf(arg)) { \ - fprintf(stderr, "Check failed: isinf(%s)\n", #arg); \ - exit(1); \ - } \ - } while (0) - -#define EXPECT_DOUBLE_EQ(val1, val2) \ - do { \ - if (((val1) < (val2) - 0.001 || (val1) > (val2) + 0.001)) { \ - fprintf(stderr, "Check failed: %s == %s\n", #val1, #val2); \ - exit(1); \ - } \ - } while (0) - -#define EXPECT_STREQ(val1, val2) \ - do { \ - if (strcmp((val1), (val2)) != 0) { \ - fprintf(stderr, "Check failed: streq(%s, %s)\n", #val1, #val2); \ - exit(1); \ - } \ - } while (0) - -vector g_testlist; // the tests to run - -#define TEST(a, b) \ - struct Test_##a##_##b { \ - Test_##a##_##b() { g_testlist.push_back(&Run); } \ - static void Run() { FlagSaver fs; RunTest(); } \ - static void RunTest(); \ - }; \ - static Test_##a##_##b g_test_##a##_##b; \ - void Test_##a##_##b::RunTest() - - -static inline int RUN_ALL_TESTS() { - vector::const_iterator it; - for (it = g_testlist.begin(); it != g_testlist.end(); ++it) { - (*it)(); - } - fprintf(stderr, "Passed %d tests\n\nPASS\n", (int)g_testlist.size()); - return 0; -} - -_END_GOOGLE_NAMESPACE_ - -#endif // ! HAVE_LIB_GTEST - -_START_GOOGLE_NAMESPACE_ - -static bool g_called_abort; -static jmp_buf g_jmp_buf; -static inline void CalledAbort() { - g_called_abort = true; - longjmp(g_jmp_buf, 1); -} - -#ifdef OS_WINDOWS -// TODO(hamaji): Death test somehow doesn't work in Windows. -#define ASSERT_DEATH(fn, msg) -#else -#define ASSERT_DEATH(fn, msg) \ - do { \ - g_called_abort = false; \ - /* in logging.cc */ \ - void (*original_logging_fail_func)() = g_logging_fail_func; \ - g_logging_fail_func = &CalledAbort; \ - if (!setjmp(g_jmp_buf)) fn; \ - /* set back to their default */ \ - g_logging_fail_func = original_logging_fail_func; \ - if (!g_called_abort) { \ - fprintf(stderr, "Function didn't die (%s): %s\n", msg, #fn); \ - exit(1); \ - } \ - } while (0) -#endif - -#ifdef NDEBUG -#define ASSERT_DEBUG_DEATH(fn, msg) -#else -#define ASSERT_DEBUG_DEATH(fn, msg) ASSERT_DEATH(fn, msg) -#endif // NDEBUG - -// Benchmark tools. - -#define BENCHMARK(n) static BenchmarkRegisterer __benchmark_ ## n (#n, &n); - -map g_benchlist; // the benchmarks to run - -class BenchmarkRegisterer { - public: - BenchmarkRegisterer(const char* name, void (*function)(int iters)) { - EXPECT_TRUE(g_benchlist.insert(std::make_pair(name, function)).second); - } -}; - -static inline void RunSpecifiedBenchmarks() { - if (!FLAGS_run_benchmark) { - return; - } - - int iter_cnt = FLAGS_benchmark_iters; - puts("Benchmark\tTime(ns)\tIterations"); - for (map::const_iterator iter = g_benchlist.begin(); - iter != g_benchlist.end(); - ++iter) { - clock_t start = clock(); - iter->second(iter_cnt); - double elapsed_ns = - ((double)clock() - start) / CLOCKS_PER_SEC * 1000*1000*1000; - printf("%s\t%8.2lf\t%10d\n", - iter->first.c_str(), elapsed_ns / iter_cnt, iter_cnt); - } - puts(""); -} - -// ---------------------------------------------------------------------- -// Golden file functions -// ---------------------------------------------------------------------- - -class CapturedStream { - public: - CapturedStream(int fd, const string & filename) : - fd_(fd), - uncaptured_fd_(-1), - filename_(filename) { - Capture(); - } - - ~CapturedStream() { - if (uncaptured_fd_ != -1) { - CHECK(close(uncaptured_fd_) != -1); - } - } - - // Start redirecting output to a file - void Capture() { - // Keep original stream for later - CHECK(uncaptured_fd_ == -1) << ", Stream " << fd_ << " already captured!"; - uncaptured_fd_ = dup(fd_); - CHECK(uncaptured_fd_ != -1); - - // Open file to save stream to - int cap_fd = open(filename_.c_str(), - O_CREAT | O_TRUNC | O_WRONLY, - S_IRUSR | S_IWUSR); - CHECK(cap_fd != -1); - - // Send stdout/stderr to this file - fflush(NULL); - CHECK(dup2(cap_fd, fd_) != -1); - CHECK(close(cap_fd) != -1); - } - - // Remove output redirection - void StopCapture() { - // Restore original stream - if (uncaptured_fd_ != -1) { - fflush(NULL); - CHECK(dup2(uncaptured_fd_, fd_) != -1); - } - } - - const string & filename() const { return filename_; } - - private: - int fd_; // file descriptor being captured - int uncaptured_fd_; // where the stream was originally being sent to - string filename_; // file where stream is being saved -}; -static CapturedStream * s_captured_streams[STDERR_FILENO+1]; -// Redirect a file descriptor to a file. -// fd - Should be STDOUT_FILENO or STDERR_FILENO -// filename - File where output should be stored -static inline void CaptureTestOutput(int fd, const string & filename) { - CHECK((fd == STDOUT_FILENO) || (fd == STDERR_FILENO)); - CHECK(s_captured_streams[fd] == NULL); - s_captured_streams[fd] = new CapturedStream(fd, filename); -} -static inline void CaptureTestStderr() { - CaptureTestOutput(STDERR_FILENO, FLAGS_test_tmpdir + "/captured.err"); -} -// Return the size (in bytes) of a file -static inline size_t GetFileSize(FILE * file) { - fseek(file, 0, SEEK_END); - return static_cast(ftell(file)); -} -// Read the entire content of a file as a string -static inline string ReadEntireFile(FILE * file) { - const size_t file_size = GetFileSize(file); - char * const buffer = new char[file_size]; - - size_t bytes_last_read = 0; // # of bytes read in the last fread() - size_t bytes_read = 0; // # of bytes read so far - - fseek(file, 0, SEEK_SET); - - // Keep reading the file until we cannot read further or the - // pre-determined file size is reached. - do { - bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); - bytes_read += bytes_last_read; - } while (bytes_last_read > 0 && bytes_read < file_size); - - const string content = string(buffer, buffer+bytes_read); - delete[] buffer; - - return content; -} -// Get the captured stdout (when fd is STDOUT_FILENO) or stderr (when -// fd is STDERR_FILENO) as a string -static inline string GetCapturedTestOutput(int fd) { - CHECK(fd == STDOUT_FILENO || fd == STDERR_FILENO); - CapturedStream * const cap = s_captured_streams[fd]; - CHECK(cap) - << ": did you forget CaptureTestStdout() or CaptureTestStderr()?"; - - // Make sure everything is flushed. - cap->StopCapture(); - - // Read the captured file. - FILE * const file = fopen(cap->filename().c_str(), "r"); - const string content = ReadEntireFile(file); - fclose(file); - - delete cap; - s_captured_streams[fd] = NULL; - - return content; -} -// Get the captured stderr of a test as a string. -static inline string GetCapturedTestStderr() { - return GetCapturedTestOutput(STDERR_FILENO); -} - -// Check if the string is [IWEF](\d{4}|DATE) -static inline bool IsLoggingPrefix(const string& s) { - if (s.size() != 5) return false; - if (!strchr("IWEF", s[0])) return false; - for (int i = 1; i <= 4; ++i) { - if (!isdigit(s[i]) && s[i] != "DATE"[i-1]) return false; - } - return true; -} - -// Convert log output into normalized form. -// -// Example: -// I0102 030405 logging_unittest.cc:345] RAW: vlog -1 -// => IDATE TIME__ logging_unittest.cc:LINE] RAW: vlog -1 -static inline string MungeLine(const string& line) { - std::istringstream iss(line); - string before, logcode_date, time, thread_lineinfo; - iss >> logcode_date; - while (!IsLoggingPrefix(logcode_date)) { - before += " " + logcode_date; - if (!(iss >> logcode_date)) { - // We cannot find the header of log output. - return before; - } - } - if (!before.empty()) before += " "; - iss >> time; - iss >> thread_lineinfo; - CHECK(!thread_lineinfo.empty()); - if (thread_lineinfo[thread_lineinfo.size() - 1] != ']') { - // We found thread ID. - string tmp; - iss >> tmp; - CHECK(!tmp.empty()); - CHECK_EQ(']', tmp[tmp.size() - 1]); - thread_lineinfo = "THREADID " + tmp; - } - size_t index = thread_lineinfo.find(':'); - CHECK_NE(string::npos, index); - thread_lineinfo = thread_lineinfo.substr(0, index+1) + "LINE]"; - string rest; - std::getline(iss, rest); - return (before + logcode_date[0] + "DATE TIME__ " + thread_lineinfo + - MungeLine(rest)); -} - -static inline void StringReplace(string* str, - const string& oldsub, - const string& newsub) { - size_t pos = str->find(oldsub); - if (pos != string::npos) { - str->replace(pos, oldsub.size(), newsub.c_str()); - } -} - -static inline string Munge(const string& filename) { - FILE* fp = fopen(filename.c_str(), "rb"); - CHECK(fp != NULL) << filename << ": couldn't open"; - char buf[4096]; - string result; - while (fgets(buf, 4095, fp)) { - string line = MungeLine(buf); - char null_str[256]; - char ptr_str[256]; - sprintf(null_str, "%p", static_cast(NULL)); - sprintf(ptr_str, "%p", reinterpret_cast(PTR_TEST_VALUE)); - - StringReplace(&line, "__NULLP__", null_str); - StringReplace(&line, "__PTRTEST__", ptr_str); - - StringReplace(&line, "__SUCCESS__", StrError(0)); - StringReplace(&line, "__ENOENT__", StrError(ENOENT)); - StringReplace(&line, "__EINTR__", StrError(EINTR)); - StringReplace(&line, "__ENXIO__", StrError(ENXIO)); - StringReplace(&line, "__ENOEXEC__", StrError(ENOEXEC)); - result += line + "\n"; - } - fclose(fp); - return result; -} - -static inline void WriteToFile(const string& body, const string& file) { - FILE* fp = fopen(file.c_str(), "wb"); - fwrite(body.data(), 1, body.size(), fp); - fclose(fp); -} - -static inline bool MungeAndDiffTestStderr(const string& golden_filename) { - CapturedStream* cap = s_captured_streams[STDERR_FILENO]; - CHECK(cap) << ": did you forget CaptureTestStderr()?"; - - cap->StopCapture(); - - // Run munge - const string captured = Munge(cap->filename()); - const string golden = Munge(golden_filename); - if (captured != golden) { - fprintf(stderr, - "Test with golden file failed. We'll try to show the diff:\n"); - string munged_golden = golden_filename + ".munged"; - WriteToFile(golden, munged_golden); - string munged_captured = cap->filename() + ".munged"; - WriteToFile(captured, munged_captured); -#ifdef OS_WINDOWS - string diffcmd("fc " + munged_golden + " " + munged_captured); -#else - string diffcmd("diff -u " + munged_golden + " " + munged_captured); -#endif - if (system(diffcmd.c_str()) != 0) { - fprintf(stderr, "diff command was failed.\n"); - } - unlink(munged_golden.c_str()); - unlink(munged_captured.c_str()); - return false; - } - LOG(INFO) << "Diff was successful"; - return true; -} - -// Save flags used from logging_unittest.cc. -#ifndef HAVE_LIB_GFLAGS -struct FlagSaver { - FlagSaver() - : v_(FLAGS_v), - stderrthreshold_(FLAGS_stderrthreshold), - logtostderr_(FLAGS_logtostderr), - alsologtostderr_(FLAGS_alsologtostderr) {} - ~FlagSaver() { - FLAGS_v = v_; - FLAGS_stderrthreshold = stderrthreshold_; - FLAGS_logtostderr = logtostderr_; - FLAGS_alsologtostderr = alsologtostderr_; - } - int v_; - int stderrthreshold_; - bool logtostderr_; - bool alsologtostderr_; -}; -#endif - -class Thread { - public: - virtual ~Thread() {} - - void SetJoinable(bool) {} -#if defined(OS_WINDOWS) && !defined(OS_CYGWIN) - void Start() { - handle_ = CreateThread(NULL, - 0, - (LPTHREAD_START_ROUTINE)&Thread::InvokeThread, - (LPVOID)this, - 0, - &th_); - CHECK(handle_) << "CreateThread"; - } - void Join() { - WaitForSingleObject(handle_, INFINITE); - } -#elif defined(HAVE_PTHREAD) - void Start() { - pthread_create(&th_, NULL, &Thread::InvokeThread, this); - } - void Join() { - pthread_join(th_, NULL); - } -#else -# error No thread implementation. -#endif - - protected: - virtual void Run() = 0; - - private: - static void* InvokeThread(void* self) { - ((Thread*)self)->Run(); - return NULL; - } - -#if defined(OS_WINDOWS) && !defined(OS_CYGWIN) - HANDLE handle_; - DWORD th_; -#else - pthread_t th_; -#endif -}; - -static inline void SleepForMilliseconds(int t) { -#ifndef OS_WINDOWS - usleep(t * 1000); -#else - Sleep(t); -#endif -} - -// Add hook for operator new to ensure there are no memory allocation. - -void (*g_new_hook)() = NULL; - -_END_GOOGLE_NAMESPACE_ - -void* operator new(size_t size) { - if (GOOGLE_NAMESPACE::g_new_hook) { - GOOGLE_NAMESPACE::g_new_hook(); - } - return malloc(size); -} - -void* operator new[](size_t size) { - return ::operator new(size); -} - -void operator delete(void* p) { - free(p); -} - -void operator delete[](void* p) { - ::operator delete(p); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging.cc deleted file mode 100644 index 0c86cf62296..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging.cc +++ /dev/null @@ -1,2177 +0,0 @@ -// Copyright (c) 1999, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite() - -#include "utilities.h" - -#include -#include -#include -#include -#ifdef HAVE_UNISTD_H -# include // For _exit. -#endif -#include -#include -#include -#ifdef HAVE_SYS_UTSNAME_H -# include // For uname. -#endif -#include -#include -#include -#include -#include -#ifdef HAVE_PWD_H -# include -#endif -#ifdef HAVE_SYSLOG_H -# include -#endif -#include -#include // for errno -#include -#include "base/commandlineflags.h" // to get the program name -#include "glog/logging.h" -#include "glog/raw_logging.h" -#include "base/googleinit.h" - -#ifdef HAVE_STACKTRACE -# include "stacktrace.h" -#endif - -using std::string; -using std::vector; -using std::setw; -using std::setfill; -using std::hex; -using std::dec; -using std::min; -using std::ostream; -using std::ostringstream; - -using std::FILE; -using std::fwrite; -using std::fclose; -using std::fflush; -using std::fprintf; -using std::perror; - -#ifdef __QNX__ -using std::fdopen; -#endif - -#ifdef _WIN32 -#define fdopen _fdopen -#endif - -// There is no thread annotation support. -#define EXCLUSIVE_LOCKS_REQUIRED(mu) - -static bool BoolFromEnv(const char *varname, bool defval) { - const char* const valstr = getenv(varname); - if (!valstr) { - return defval; - } - return memchr("tTyY1\0", valstr[0], 6) != NULL; -} - -GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false), - "log messages go to stderr instead of logfiles"); -GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false), - "log messages go to stderr in addition to logfiles"); -GLOG_DEFINE_bool(colorlogtostderr, false, - "color messages logged to stderr (if supported by terminal)"); -#ifdef OS_LINUX -GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. " - "Logs can grow very quickly and they are rarely read before they " - "need to be evicted from memory. Instead, drop them from memory " - "as soon as they are flushed to disk."); -#endif - -// By default, errors (including fatal errors) get logged to stderr as -// well as the file. -// -// The default is ERROR instead of FATAL so that users can see problems -// when they run a program without having to look in another file. -DEFINE_int32(stderrthreshold, - GOOGLE_NAMESPACE::GLOG_ERROR, - "log messages at or above this level are copied to stderr in " - "addition to logfiles. This flag obsoletes --alsologtostderr."); - -GLOG_DEFINE_string(alsologtoemail, "", - "log messages go to these email addresses " - "in addition to logfiles"); -GLOG_DEFINE_bool(log_prefix, true, - "Prepend the log prefix to the start of each log line"); -GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't " - "actually get logged anywhere"); -GLOG_DEFINE_int32(logbuflevel, 0, - "Buffer log messages logged at this level or lower" - " (-1 means don't buffer; 0 means buffer INFO only;" - " ...)"); -GLOG_DEFINE_int32(logbufsecs, 30, - "Buffer log messages for at most this many seconds"); -GLOG_DEFINE_int32(logemaillevel, 999, - "Email log messages logged at this level or higher" - " (0 means email all; 3 means email FATAL only;" - " ...)"); -GLOG_DEFINE_string(logmailer, "/bin/mail", - "Mailer used to send logging email"); - -// Compute the default value for --log_dir -static const char* DefaultLogDir() { - const char* env; - env = getenv("GOOGLE_LOG_DIR"); - if (env != NULL && env[0] != '\0') { - return env; - } - env = getenv("TEST_TMPDIR"); - if (env != NULL && env[0] != '\0') { - return env; - } - return ""; -} - -GLOG_DEFINE_int32(logfile_mode, 0664, "Log file mode/permissions."); - -GLOG_DEFINE_string(log_dir, DefaultLogDir(), - "If specified, logfiles are written into this directory instead " - "of the default logging directory."); -GLOG_DEFINE_string(log_link, "", "Put additional links to the log " - "files in this directory"); - -GLOG_DEFINE_int32(max_log_size, 1800, - "approx. maximum log file size (in MB). A value of 0 will " - "be silently overridden to 1."); - -GLOG_DEFINE_bool(stop_logging_if_full_disk, false, - "Stop attempting to log to disk if the disk is full."); - -GLOG_DEFINE_string(log_backtrace_at, "", - "Emit a backtrace when logging at file:linenum."); - -// TODO(hamaji): consider windows -#define PATH_SEPARATOR '/' - -#ifndef HAVE_PREAD -#if defined(OS_WINDOWS) -#include -#define ssize_t SSIZE_T -#endif -static ssize_t pread(int fd, void* buf, size_t count, off_t offset) { - off_t orig_offset = lseek(fd, 0, SEEK_CUR); - if (orig_offset == (off_t)-1) - return -1; - if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) - return -1; - ssize_t len = read(fd, buf, count); - if (len < 0) - return len; - if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) - return -1; - return len; -} -#endif // !HAVE_PREAD - -#ifndef HAVE_PWRITE -static ssize_t pwrite(int fd, void* buf, size_t count, off_t offset) { - off_t orig_offset = lseek(fd, 0, SEEK_CUR); - if (orig_offset == (off_t)-1) - return -1; - if (lseek(fd, offset, SEEK_CUR) == (off_t)-1) - return -1; - ssize_t len = write(fd, buf, count); - if (len < 0) - return len; - if (lseek(fd, orig_offset, SEEK_SET) == (off_t)-1) - return -1; - return len; -} -#endif // !HAVE_PWRITE - -static void GetHostName(string* hostname) { -#if defined(HAVE_SYS_UTSNAME_H) - struct utsname buf; - if (0 != uname(&buf)) { - // ensure null termination on failure - *buf.nodename = '\0'; - } - *hostname = buf.nodename; -#elif defined(OS_WINDOWS) - char buf[MAX_COMPUTERNAME_LENGTH + 1]; - DWORD len = MAX_COMPUTERNAME_LENGTH + 1; - if (GetComputerNameA(buf, &len)) { - *hostname = buf; - } else { - hostname->clear(); - } -#else -# warning There is no way to retrieve the host name. - *hostname = "(unknown)"; -#endif -} - -// Returns true iff terminal supports using colors in output. -static bool TerminalSupportsColor() { - bool term_supports_color = false; -#ifdef OS_WINDOWS - // on Windows TERM variable is usually not set, but the console does - // support colors. - term_supports_color = true; -#else - // On non-Windows platforms, we rely on the TERM variable. - const char* const term = getenv("TERM"); - if (term != NULL && term[0] != '\0') { - term_supports_color = - !strcmp(term, "xterm") || - !strcmp(term, "xterm-color") || - !strcmp(term, "xterm-256color") || - !strcmp(term, "screen-256color") || - !strcmp(term, "konsole") || - !strcmp(term, "konsole-16color") || - !strcmp(term, "konsole-256color") || - !strcmp(term, "screen") || - !strcmp(term, "linux") || - !strcmp(term, "cygwin"); - } -#endif - return term_supports_color; -} - -_START_GOOGLE_NAMESPACE_ - -enum GLogColor { - COLOR_DEFAULT, - COLOR_RED, - COLOR_GREEN, - COLOR_YELLOW -}; - -static GLogColor SeverityToColor(LogSeverity severity) { - assert(severity >= 0 && severity < NUM_SEVERITIES); - GLogColor color = COLOR_DEFAULT; - switch (severity) { - case GLOG_INFO: - color = COLOR_DEFAULT; - break; - case GLOG_WARNING: - color = COLOR_YELLOW; - break; - case GLOG_ERROR: - case GLOG_FATAL: - color = COLOR_RED; - break; - default: - // should never get here. - assert(false); - } - return color; -} - -#ifdef OS_WINDOWS - -// Returns the character attribute for the given color. -static WORD GetColorAttribute(GLogColor color) { - switch (color) { - case COLOR_RED: return FOREGROUND_RED; - case COLOR_GREEN: return FOREGROUND_GREEN; - case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; - default: return 0; - } -} - -#else - -// Returns the ANSI color code for the given color. -static const char* GetAnsiColorCode(GLogColor color) { - switch (color) { - case COLOR_RED: return "1"; - case COLOR_GREEN: return "2"; - case COLOR_YELLOW: return "3"; - case COLOR_DEFAULT: return ""; - }; - return NULL; // stop warning about return type. -} - -#endif // OS_WINDOWS - -// Safely get max_log_size, overriding to 1 if it somehow gets defined as 0 -static int32 MaxLogSize() { - return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1); -} - -// An arbitrary limit on the length of a single log message. This -// is so that streaming can be done more efficiently. -const size_t LogMessage::kMaxLogMessageLen = 30000; - -struct LogMessage::LogMessageData { - LogMessageData(); - - int preserved_errno_; // preserved errno - // Buffer space; contains complete message text. - char message_text_[LogMessage::kMaxLogMessageLen+1]; - LogStream stream_; - char severity_; // What level is this LogMessage logged at? - int line_; // line number where logging call is. - void (LogMessage::*send_method_)(); // Call this in destructor to send - union { // At most one of these is used: union to keep the size low. - LogSink* sink_; // NULL or sink to send message to - std::vector* outvec_; // NULL or vector to push message onto - std::string* message_; // NULL or string to write message into - }; - time_t timestamp_; // Time of creation of LogMessage - struct ::tm tm_time_; // Time of creation of LogMessage - size_t num_prefix_chars_; // # of chars of prefix in this message - size_t num_chars_to_log_; // # of chars of msg to send to log - size_t num_chars_to_syslog_; // # of chars of msg to send to syslog - const char* basename_; // basename of file that called LOG - const char* fullname_; // fullname of file that called LOG - bool has_been_flushed_; // false => data has not been flushed - bool first_fatal_; // true => this was first fatal msg - - private: - LogMessageData(const LogMessageData&); - void operator=(const LogMessageData&); -}; - -// A mutex that allows only one thread to log at a time, to keep things from -// getting jumbled. Some other very uncommon logging operations (like -// changing the destination file for log messages of a given severity) also -// lock this mutex. Please be sure that anybody who might possibly need to -// lock it does so. -static Mutex log_mutex; - -// Number of messages sent at each severity. Under log_mutex. -int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0}; - -// Globally disable log writing (if disk is full) -static bool stop_writing = false; - -const char*const LogSeverityNames[NUM_SEVERITIES] = { - "INFO", "WARNING", "ERROR", "FATAL" -}; - -// Has the user called SetExitOnDFatal(true)? -static bool exit_on_dfatal = true; - -const char* GetLogSeverityName(LogSeverity severity) { - return LogSeverityNames[severity]; -} - -static bool SendEmailInternal(const char*dest, const char *subject, - const char*body, bool use_logging); - -base::Logger::~Logger() { -} - -namespace { - -// Encapsulates all file-system related state -class LogFileObject : public base::Logger { - public: - LogFileObject(LogSeverity severity, const char* base_filename); - ~LogFileObject(); - - virtual void Write(bool force_flush, // Should we force a flush here? - time_t timestamp, // Timestamp for this entry - const char* message, - int message_len); - - // Configuration options - void SetBasename(const char* basename); - void SetExtension(const char* ext); - void SetSymlinkBasename(const char* symlink_basename); - - // Normal flushing routine - virtual void Flush(); - - // It is the actual file length for the system loggers, - // i.e., INFO, ERROR, etc. - virtual uint32 LogSize() { - MutexLock l(&lock_); - return file_length_; - } - - // Internal flush routine. Exposed so that FlushLogFilesUnsafe() - // can avoid grabbing a lock. Usually Flush() calls it after - // acquiring lock_. - void FlushUnlocked(); - - private: - static const uint32 kRolloverAttemptFrequency = 0x20; - - Mutex lock_; - bool base_filename_selected_; - string base_filename_; - string symlink_basename_; - string filename_extension_; // option users can specify (eg to add port#) - FILE* file_; - LogSeverity severity_; - uint32 bytes_since_flush_; - uint32 dropped_mem_length_; - uint32 file_length_; - unsigned int rollover_attempt_; - int64 next_flush_time_; // cycle count at which to flush log - - // Actually create a logfile using the value of base_filename_ and the - // supplied argument time_pid_string - // REQUIRES: lock_ is held - bool CreateLogfile(const string& time_pid_string); -}; - -} // namespace - -class LogDestination { - public: - friend class LogMessage; - friend void ReprintFatalMessage(); - friend base::Logger* base::GetLogger(LogSeverity); - friend void base::SetLogger(LogSeverity, base::Logger*); - - // These methods are just forwarded to by their global versions. - static void SetLogDestination(LogSeverity severity, - const char* base_filename); - static void SetLogSymlink(LogSeverity severity, - const char* symlink_basename); - static void AddLogSink(LogSink *destination); - static void RemoveLogSink(LogSink *destination); - static void SetLogFilenameExtension(const char* filename_extension); - static void SetStderrLogging(LogSeverity min_severity); - static void SetEmailLogging(LogSeverity min_severity, const char* addresses); - static void LogToStderr(); - // Flush all log files that are at least at the given severity level - static void FlushLogFiles(int min_severity); - static void FlushLogFilesUnsafe(int min_severity); - - // we set the maximum size of our packet to be 1400, the logic being - // to prevent fragmentation. - // Really this number is arbitrary. - static const int kNetworkBytes = 1400; - - static const string& hostname(); - static const bool& terminal_supports_color() { - return terminal_supports_color_; - } - - static void DeleteLogDestinations(); - - private: - LogDestination(LogSeverity severity, const char* base_filename); - ~LogDestination() { } - - // Take a log message of a particular severity and log it to stderr - // iff it's of a high enough severity to deserve it. - static void MaybeLogToStderr(LogSeverity severity, const char* message, - size_t len); - - // Take a log message of a particular severity and log it to email - // iff it's of a high enough severity to deserve it. - static void MaybeLogToEmail(LogSeverity severity, const char* message, - size_t len); - // Take a log message of a particular severity and log it to a file - // iff the base filename is not "" (which means "don't log to me") - static void MaybeLogToLogfile(LogSeverity severity, - time_t timestamp, - const char* message, size_t len); - // Take a log message of a particular severity and log it to the file - // for that severity and also for all files with severity less than - // this severity. - static void LogToAllLogfiles(LogSeverity severity, - time_t timestamp, - const char* message, size_t len); - - // Send logging info to all registered sinks. - static void LogToSinks(LogSeverity severity, - const char *full_filename, - const char *base_filename, - int line, - const struct ::tm* tm_time, - const char* message, - size_t message_len); - - // Wait for all registered sinks via WaitTillSent - // including the optional one in "data". - static void WaitForSinks(LogMessage::LogMessageData* data); - - static LogDestination* log_destination(LogSeverity severity); - - LogFileObject fileobject_; - base::Logger* logger_; // Either &fileobject_, or wrapper around it - - static LogDestination* log_destinations_[NUM_SEVERITIES]; - static LogSeverity email_logging_severity_; - static string addresses_; - static string hostname_; - static bool terminal_supports_color_; - - // arbitrary global logging destinations. - static vector* sinks_; - - // Protects the vector sinks_, - // but not the LogSink objects its elements reference. - static Mutex sink_mutex_; - - // Disallow - LogDestination(const LogDestination&); - LogDestination& operator=(const LogDestination&); -}; - -// Errors do not get logged to email by default. -LogSeverity LogDestination::email_logging_severity_ = 99999; - -string LogDestination::addresses_; -string LogDestination::hostname_; - -vector* LogDestination::sinks_ = NULL; -Mutex LogDestination::sink_mutex_; -bool LogDestination::terminal_supports_color_ = TerminalSupportsColor(); - -/* static */ -const string& LogDestination::hostname() { - if (hostname_.empty()) { - GetHostName(&hostname_); - if (hostname_.empty()) { - hostname_ = "(unknown)"; - } - } - return hostname_; -} - -LogDestination::LogDestination(LogSeverity severity, - const char* base_filename) - : fileobject_(severity, base_filename), - logger_(&fileobject_) { -} - -inline void LogDestination::FlushLogFilesUnsafe(int min_severity) { - // assume we have the log_mutex or we simply don't care - // about it - for (int i = min_severity; i < NUM_SEVERITIES; i++) { - LogDestination* log = log_destinations_[i]; - if (log != NULL) { - // Flush the base fileobject_ logger directly instead of going - // through any wrappers to reduce chance of deadlock. - log->fileobject_.FlushUnlocked(); - } - } -} - -inline void LogDestination::FlushLogFiles(int min_severity) { - // Prevent any subtle race conditions by wrapping a mutex lock around - // all this stuff. - MutexLock l(&log_mutex); - for (int i = min_severity; i < NUM_SEVERITIES; i++) { - LogDestination* log = log_destination(i); - if (log != NULL) { - log->logger_->Flush(); - } - } -} - -inline void LogDestination::SetLogDestination(LogSeverity severity, - const char* base_filename) { - assert(severity >= 0 && severity < NUM_SEVERITIES); - // Prevent any subtle race conditions by wrapping a mutex lock around - // all this stuff. - MutexLock l(&log_mutex); - log_destination(severity)->fileobject_.SetBasename(base_filename); -} - -inline void LogDestination::SetLogSymlink(LogSeverity severity, - const char* symlink_basename) { - CHECK_GE(severity, 0); - CHECK_LT(severity, NUM_SEVERITIES); - MutexLock l(&log_mutex); - log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename); -} - -inline void LogDestination::AddLogSink(LogSink *destination) { - // Prevent any subtle race conditions by wrapping a mutex lock around - // all this stuff. - MutexLock l(&sink_mutex_); - if (!sinks_) sinks_ = new vector; - sinks_->push_back(destination); -} - -inline void LogDestination::RemoveLogSink(LogSink *destination) { - // Prevent any subtle race conditions by wrapping a mutex lock around - // all this stuff. - MutexLock l(&sink_mutex_); - // This doesn't keep the sinks in order, but who cares? - if (sinks_) { - for (int i = sinks_->size() - 1; i >= 0; i--) { - if ((*sinks_)[i] == destination) { - (*sinks_)[i] = (*sinks_)[sinks_->size() - 1]; - sinks_->pop_back(); - break; - } - } - } -} - -inline void LogDestination::SetLogFilenameExtension(const char* ext) { - // Prevent any subtle race conditions by wrapping a mutex lock around - // all this stuff. - MutexLock l(&log_mutex); - for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) { - log_destination(severity)->fileobject_.SetExtension(ext); - } -} - -inline void LogDestination::SetStderrLogging(LogSeverity min_severity) { - assert(min_severity >= 0 && min_severity < NUM_SEVERITIES); - // Prevent any subtle race conditions by wrapping a mutex lock around - // all this stuff. - MutexLock l(&log_mutex); - FLAGS_stderrthreshold = min_severity; -} - -inline void LogDestination::LogToStderr() { - // *Don't* put this stuff in a mutex lock, since SetStderrLogging & - // SetLogDestination already do the locking! - SetStderrLogging(0); // thus everything is "also" logged to stderr - for ( int i = 0; i < NUM_SEVERITIES; ++i ) { - SetLogDestination(i, ""); // "" turns off logging to a logfile - } -} - -inline void LogDestination::SetEmailLogging(LogSeverity min_severity, - const char* addresses) { - assert(min_severity >= 0 && min_severity < NUM_SEVERITIES); - // Prevent any subtle race conditions by wrapping a mutex lock around - // all this stuff. - MutexLock l(&log_mutex); - LogDestination::email_logging_severity_ = min_severity; - LogDestination::addresses_ = addresses; -} - -static void ColoredWriteToStderr(LogSeverity severity, - const char* message, size_t len) { - const GLogColor color = - (LogDestination::terminal_supports_color() && FLAGS_colorlogtostderr) ? - SeverityToColor(severity) : COLOR_DEFAULT; - - // Avoid using cerr from this module since we may get called during - // exit code, and cerr may be partially or fully destroyed by then. - if (COLOR_DEFAULT == color) { - fwrite(message, len, 1, stderr); - return; - } -#ifdef OS_WINDOWS - const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE); - - // Gets the current text color. - CONSOLE_SCREEN_BUFFER_INFO buffer_info; - GetConsoleScreenBufferInfo(stderr_handle, &buffer_info); - const WORD old_color_attrs = buffer_info.wAttributes; - - // We need to flush the stream buffers into the console before each - // SetConsoleTextAttribute call lest it affect the text that is already - // printed but has not yet reached the console. - fflush(stderr); - SetConsoleTextAttribute(stderr_handle, - GetColorAttribute(color) | FOREGROUND_INTENSITY); - fwrite(message, len, 1, stderr); - fflush(stderr); - // Restores the text color. - SetConsoleTextAttribute(stderr_handle, old_color_attrs); -#else - fprintf(stderr, "\033[0;3%sm", GetAnsiColorCode(color)); - fwrite(message, len, 1, stderr); - fprintf(stderr, "\033[m"); // Resets the terminal to default. -#endif // OS_WINDOWS -} - -static void WriteToStderr(const char* message, size_t len) { - // Avoid using cerr from this module since we may get called during - // exit code, and cerr may be partially or fully destroyed by then. - fwrite(message, len, 1, stderr); -} - -inline void LogDestination::MaybeLogToStderr(LogSeverity severity, - const char* message, size_t len) { - if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) { - ColoredWriteToStderr(severity, message, len); -#ifdef OS_WINDOWS - // On Windows, also output to the debugger - ::OutputDebugStringA(string(message,len).c_str()); -#endif - } -} - - -inline void LogDestination::MaybeLogToEmail(LogSeverity severity, - const char* message, size_t len) { - if (severity >= email_logging_severity_ || - severity >= FLAGS_logemaillevel) { - string to(FLAGS_alsologtoemail); - if (!addresses_.empty()) { - if (!to.empty()) { - to += ","; - } - to += addresses_; - } - const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " + - glog_internal_namespace_::ProgramInvocationShortName()); - string body(hostname()); - body += "\n\n"; - body.append(message, len); - - // should NOT use SendEmail(). The caller of this function holds the - // log_mutex and SendEmail() calls LOG/VLOG which will block trying to - // acquire the log_mutex object. Use SendEmailInternal() and set - // use_logging to false. - SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false); - } -} - - -inline void LogDestination::MaybeLogToLogfile(LogSeverity severity, - time_t timestamp, - const char* message, - size_t len) { - const bool should_flush = severity > FLAGS_logbuflevel; - LogDestination* destination = log_destination(severity); - destination->logger_->Write(should_flush, timestamp, message, len); -} - -inline void LogDestination::LogToAllLogfiles(LogSeverity severity, - time_t timestamp, - const char* message, - size_t len) { - - if ( FLAGS_logtostderr ) { // global flag: never log to file - ColoredWriteToStderr(severity, message, len); - } else { - for (int i = severity; i >= 0; --i) - LogDestination::MaybeLogToLogfile(i, timestamp, message, len); - } -} - -inline void LogDestination::LogToSinks(LogSeverity severity, - const char *full_filename, - const char *base_filename, - int line, - const struct ::tm* tm_time, - const char* message, - size_t message_len) { - ReaderMutexLock l(&sink_mutex_); - if (sinks_) { - for (int i = sinks_->size() - 1; i >= 0; i--) { - (*sinks_)[i]->send(severity, full_filename, base_filename, - line, tm_time, message, message_len); - } - } -} - -inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) { - ReaderMutexLock l(&sink_mutex_); - if (sinks_) { - for (int i = sinks_->size() - 1; i >= 0; i--) { - (*sinks_)[i]->WaitTillSent(); - } - } - const bool send_to_sink = - (data->send_method_ == &LogMessage::SendToSink) || - (data->send_method_ == &LogMessage::SendToSinkAndLog); - if (send_to_sink && data->sink_ != NULL) { - data->sink_->WaitTillSent(); - } -} - -LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES]; - -inline LogDestination* LogDestination::log_destination(LogSeverity severity) { - assert(severity >=0 && severity < NUM_SEVERITIES); - if (!log_destinations_[severity]) { - log_destinations_[severity] = new LogDestination(severity, NULL); - } - return log_destinations_[severity]; -} - -void LogDestination::DeleteLogDestinations() { - for (int severity = 0; severity < NUM_SEVERITIES; ++severity) { - delete log_destinations_[severity]; - log_destinations_[severity] = NULL; - } - MutexLock l(&sink_mutex_); - delete sinks_; - sinks_ = NULL; -} - -namespace { - -LogFileObject::LogFileObject(LogSeverity severity, - const char* base_filename) - : base_filename_selected_(base_filename != NULL), - base_filename_((base_filename != NULL) ? base_filename : ""), - symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()), - filename_extension_(), - file_(NULL), - severity_(severity), - bytes_since_flush_(0), - dropped_mem_length_(0), - file_length_(0), - rollover_attempt_(kRolloverAttemptFrequency-1), - next_flush_time_(0) { - assert(severity >= 0); - assert(severity < NUM_SEVERITIES); -} - -LogFileObject::~LogFileObject() { - MutexLock l(&lock_); - if (file_ != NULL) { - fclose(file_); - file_ = NULL; - } -} - -void LogFileObject::SetBasename(const char* basename) { - MutexLock l(&lock_); - base_filename_selected_ = true; - if (base_filename_ != basename) { - // Get rid of old log file since we are changing names - if (file_ != NULL) { - fclose(file_); - file_ = NULL; - rollover_attempt_ = kRolloverAttemptFrequency-1; - } - base_filename_ = basename; - } -} - -void LogFileObject::SetExtension(const char* ext) { - MutexLock l(&lock_); - if (filename_extension_ != ext) { - // Get rid of old log file since we are changing names - if (file_ != NULL) { - fclose(file_); - file_ = NULL; - rollover_attempt_ = kRolloverAttemptFrequency-1; - } - filename_extension_ = ext; - } -} - -void LogFileObject::SetSymlinkBasename(const char* symlink_basename) { - MutexLock l(&lock_); - symlink_basename_ = symlink_basename; -} - -void LogFileObject::Flush() { - MutexLock l(&lock_); - FlushUnlocked(); -} - -void LogFileObject::FlushUnlocked(){ - if (file_ != NULL) { - fflush(file_); - bytes_since_flush_ = 0; - } - // Figure out when we are due for another flush. - const int64 next = (FLAGS_logbufsecs - * static_cast(1000000)); // in usec - next_flush_time_ = CycleClock_Now() + UsecToCycles(next); -} - -bool LogFileObject::CreateLogfile(const string& time_pid_string) { - string string_filename = base_filename_+filename_extension_+ - time_pid_string; - const char* filename = string_filename.c_str(); - int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, FLAGS_logfile_mode); - if (fd == -1) return false; -#ifdef HAVE_FCNTL - // Mark the file close-on-exec. We don't really care if this fails - fcntl(fd, F_SETFD, FD_CLOEXEC); -#endif - - file_ = fdopen(fd, "a"); // Make a FILE*. - if (file_ == NULL) { // Man, we're screwed! - close(fd); - unlink(filename); // Erase the half-baked evidence: an unusable log file - return false; - } - - // We try to create a symlink called ., - // which is easier to use. (Every time we create a new logfile, - // we destroy the old symlink and create a new one, so it always - // points to the latest logfile.) If it fails, we're sad but it's - // no error. - if (!symlink_basename_.empty()) { - // take directory from filename - const char* slash = strrchr(filename, PATH_SEPARATOR); - const string linkname = - symlink_basename_ + '.' + LogSeverityNames[severity_]; - string linkpath; - if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname - linkpath += linkname; - unlink(linkpath.c_str()); // delete old one if it exists - -#if defined(OS_WINDOWS) - // TODO(hamaji): Create lnk file on Windows? -#elif defined(HAVE_UNISTD_H) - // We must have unistd.h. - // Make the symlink be relative (in the same dir) so that if the - // entire log directory gets relocated the link is still valid. - const char *linkdest = slash ? (slash + 1) : filename; - if (symlink(linkdest, linkpath.c_str()) != 0) { - // silently ignore failures - } - - // Make an additional link to the log file in a place specified by - // FLAGS_log_link, if indicated - if (!FLAGS_log_link.empty()) { - linkpath = FLAGS_log_link + "/" + linkname; - unlink(linkpath.c_str()); // delete old one if it exists - if (symlink(filename, linkpath.c_str()) != 0) { - // silently ignore failures - } - } -#endif - } - - return true; // Everything worked -} - -void LogFileObject::Write(bool force_flush, - time_t timestamp, - const char* message, - int message_len) { - MutexLock l(&lock_); - - // We don't log if the base_name_ is "" (which means "don't write") - if (base_filename_selected_ && base_filename_.empty()) { - return; - } - - if (static_cast(file_length_ >> 20) >= MaxLogSize() || - PidHasChanged()) { - if (file_ != NULL) fclose(file_); - file_ = NULL; - file_length_ = bytes_since_flush_ = dropped_mem_length_ = 0; - rollover_attempt_ = kRolloverAttemptFrequency-1; - } - - // If there's no destination file, make one before outputting - if (file_ == NULL) { - // Try to rollover the log file every 32 log messages. The only time - // this could matter would be when we have trouble creating the log - // file. If that happens, we'll lose lots of log messages, of course! - if (++rollover_attempt_ != kRolloverAttemptFrequency) return; - rollover_attempt_ = 0; - - struct ::tm tm_time; - localtime_r(×tamp, &tm_time); - - // The logfile's filename will have the date/time & pid in it - ostringstream time_pid_stream; - time_pid_stream.fill('0'); - time_pid_stream << 1900+tm_time.tm_year - << setw(2) << 1+tm_time.tm_mon - << setw(2) << tm_time.tm_mday - << '-' - << setw(2) << tm_time.tm_hour - << setw(2) << tm_time.tm_min - << setw(2) << tm_time.tm_sec - << '.' - << GetMainThreadPid(); - const string& time_pid_string = time_pid_stream.str(); - - if (base_filename_selected_) { - if (!CreateLogfile(time_pid_string)) { - perror("Could not create log file"); - fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", - time_pid_string.c_str()); - return; - } - } else { - // If no base filename for logs of this severity has been set, use a - // default base filename of - // "...log..". So - // logfiles will have names like - // webserver.examplehost.root.log.INFO.19990817-150000.4354, where - // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00), - // and 4354 is the pid of the logging process. The date & time reflect - // when the file was created for output. - // - // Where does the file get put? Successively try the directories - // "/tmp", and "." - string stripped_filename( - glog_internal_namespace_::ProgramInvocationShortName()); - string hostname; - GetHostName(&hostname); - - string uidname = MyUserName(); - // We should not call CHECK() here because this function can be - // called after holding on to log_mutex. We don't want to - // attempt to hold on to the same mutex, and get into a - // deadlock. Simply use a name like invalid-user. - if (uidname.empty()) uidname = "invalid-user"; - - stripped_filename = stripped_filename+'.'+hostname+'.' - +uidname+".log." - +LogSeverityNames[severity_]+'.'; - // We're going to (potentially) try to put logs in several different dirs - const vector & log_dirs = GetLoggingDirectories(); - - // Go through the list of dirs, and try to create the log file in each - // until we succeed or run out of options - bool success = false; - for (vector::const_iterator dir = log_dirs.begin(); - dir != log_dirs.end(); - ++dir) { - base_filename_ = *dir + "/" + stripped_filename; - if ( CreateLogfile(time_pid_string) ) { - success = true; - break; - } - } - // If we never succeeded, we have to give up - if ( success == false ) { - perror("Could not create logging file"); - fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", - time_pid_string.c_str()); - return; - } - } - - // Write a header message into the log file - ostringstream file_header_stream; - file_header_stream.fill('0'); - file_header_stream << "Log file created at: " - << 1900+tm_time.tm_year << '/' - << setw(2) << 1+tm_time.tm_mon << '/' - << setw(2) << tm_time.tm_mday - << ' ' - << setw(2) << tm_time.tm_hour << ':' - << setw(2) << tm_time.tm_min << ':' - << setw(2) << tm_time.tm_sec << '\n' - << "Running on machine: " - << LogDestination::hostname() << '\n' - << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu " - << "threadid file:line] msg" << '\n'; - const string& file_header_string = file_header_stream.str(); - - const int header_len = file_header_string.size(); - fwrite(file_header_string.data(), 1, header_len, file_); - file_length_ += header_len; - bytes_since_flush_ += header_len; - } - - // Write to LOG file - if ( !stop_writing ) { - // fwrite() doesn't return an error when the disk is full, for - // messages that are less than 4096 bytes. When the disk is full, - // it returns the message length for messages that are less than - // 4096 bytes. fwrite() returns 4096 for message lengths that are - // greater than 4096, thereby indicating an error. - errno = 0; - fwrite(message, 1, message_len, file_); - if ( FLAGS_stop_logging_if_full_disk && - errno == ENOSPC ) { // disk full, stop writing to disk - stop_writing = true; // until the disk is - return; - } else { - file_length_ += message_len; - bytes_since_flush_ += message_len; - } - } else { - if ( CycleClock_Now() >= next_flush_time_ ) - stop_writing = false; // check to see if disk has free space. - return; // no need to flush - } - - // See important msgs *now*. Also, flush logs at least every 10^6 chars, - // or every "FLAGS_logbufsecs" seconds. - if ( force_flush || - (bytes_since_flush_ >= 1000000) || - (CycleClock_Now() >= next_flush_time_) ) { - FlushUnlocked(); -#ifdef OS_LINUX - // Only consider files >= 3MiB - if (FLAGS_drop_log_memory && file_length_ >= (3 << 20)) { - // Don't evict the most recent 1-2MiB so as not to impact a tailer - // of the log file and to avoid page rounding issue on linux < 4.7 - uint32 total_drop_length = (file_length_ & ~((1 << 20) - 1)) - (1 << 20); - uint32 this_drop_length = total_drop_length - dropped_mem_length_; - if (this_drop_length >= (2 << 20)) { - // Only advise when >= 2MiB to drop - posix_fadvise(fileno(file_), dropped_mem_length_, this_drop_length, - POSIX_FADV_DONTNEED); - dropped_mem_length_ = total_drop_length; - } - } -#endif - } -} - -} // namespace - - -// Static log data space to avoid alloc failures in a LOG(FATAL) -// -// Since multiple threads may call LOG(FATAL), and we want to preserve -// the data from the first call, we allocate two sets of space. One -// for exclusive use by the first thread, and one for shared use by -// all other threads. -static Mutex fatal_msg_lock; -static CrashReason crash_reason; -static bool fatal_msg_exclusive = true; -static LogMessage::LogMessageData fatal_msg_data_exclusive; -static LogMessage::LogMessageData fatal_msg_data_shared; - -#ifdef GLOG_THREAD_LOCAL_STORAGE -// Static thread-local log data space to use, because typically at most one -// LogMessageData object exists (in this case glog makes zero heap memory -// allocations). -static GLOG_THREAD_LOCAL_STORAGE bool thread_data_available = true; - -#ifdef HAVE_ALIGNED_STORAGE -static GLOG_THREAD_LOCAL_STORAGE - std::aligned_storage::type thread_msg_data; -#else -static GLOG_THREAD_LOCAL_STORAGE - char thread_msg_data[sizeof(void*) + sizeof(LogMessage::LogMessageData)]; -#endif // HAVE_ALIGNED_STORAGE -#endif // defined(GLOG_THREAD_LOCAL_STORAGE) - -LogMessage::LogMessageData::LogMessageData() - : stream_(message_text_, LogMessage::kMaxLogMessageLen, 0) { -} - -LogMessage::LogMessage(const char* file, int line, LogSeverity severity, - int ctr, void (LogMessage::*send_method)()) - : allocated_(NULL) { - Init(file, line, severity, send_method); - data_->stream_.set_ctr(ctr); -} - -LogMessage::LogMessage(const char* file, int line, - const CheckOpString& result) - : allocated_(NULL) { - Init(file, line, GLOG_FATAL, &LogMessage::SendToLog); - stream() << "Check failed: " << (*result.str_) << " "; -} - -LogMessage::LogMessage(const char* file, int line) - : allocated_(NULL) { - Init(file, line, GLOG_INFO, &LogMessage::SendToLog); -} - -LogMessage::LogMessage(const char* file, int line, LogSeverity severity) - : allocated_(NULL) { - Init(file, line, severity, &LogMessage::SendToLog); -} - -LogMessage::LogMessage(const char* file, int line, LogSeverity severity, - LogSink* sink, bool also_send_to_log) - : allocated_(NULL) { - Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog : - &LogMessage::SendToSink); - data_->sink_ = sink; // override Init()'s setting to NULL -} - -LogMessage::LogMessage(const char* file, int line, LogSeverity severity, - vector *outvec) - : allocated_(NULL) { - Init(file, line, severity, &LogMessage::SaveOrSendToLog); - data_->outvec_ = outvec; // override Init()'s setting to NULL -} - -LogMessage::LogMessage(const char* file, int line, LogSeverity severity, - string *message) - : allocated_(NULL) { - Init(file, line, severity, &LogMessage::WriteToStringAndLog); - data_->message_ = message; // override Init()'s setting to NULL -} - -void LogMessage::Init(const char* file, - int line, - LogSeverity severity, - void (LogMessage::*send_method)()) { - allocated_ = NULL; - if (severity != GLOG_FATAL || !exit_on_dfatal) { -#ifdef GLOG_THREAD_LOCAL_STORAGE - // No need for locking, because this is thread local. - if (thread_data_available) { - thread_data_available = false; -#ifdef HAVE_ALIGNED_STORAGE - data_ = new (&thread_msg_data) LogMessageData; -#else - const uintptr_t kAlign = sizeof(void*) - 1; - - char* align_ptr = - reinterpret_cast(reinterpret_cast(thread_msg_data + kAlign) & ~kAlign); - data_ = new (align_ptr) LogMessageData; - assert(reinterpret_cast(align_ptr) % sizeof(void*) == 0); -#endif - } else { - allocated_ = new LogMessageData(); - data_ = allocated_; - } -#else // !defined(GLOG_THREAD_LOCAL_STORAGE) - allocated_ = new LogMessageData(); - data_ = allocated_; -#endif // defined(GLOG_THREAD_LOCAL_STORAGE) - data_->first_fatal_ = false; - } else { - MutexLock l(&fatal_msg_lock); - if (fatal_msg_exclusive) { - fatal_msg_exclusive = false; - data_ = &fatal_msg_data_exclusive; - data_->first_fatal_ = true; - } else { - data_ = &fatal_msg_data_shared; - data_->first_fatal_ = false; - } - } - - stream().fill('0'); - data_->preserved_errno_ = errno; - data_->severity_ = severity; - data_->line_ = line; - data_->send_method_ = send_method; - data_->sink_ = NULL; - data_->outvec_ = NULL; - WallTime now = WallTime_Now(); - data_->timestamp_ = static_cast(now); - localtime_r(&data_->timestamp_, &data_->tm_time_); - int usecs = static_cast((now - data_->timestamp_) * 1000000); - - data_->num_chars_to_log_ = 0; - data_->num_chars_to_syslog_ = 0; - data_->basename_ = const_basename(file); - data_->fullname_ = file; - data_->has_been_flushed_ = false; - - // If specified, prepend a prefix to each line. For example: - // I1018 160715 f5d4fbb0 logging.cc:1153] - // (log level, GMT month, date, time, thread_id, file basename, line) - // We exclude the thread_id for the default thread. - if (FLAGS_log_prefix && (line != kNoLogPrefix)) { - stream() << LogSeverityNames[severity][0] - << setw(2) << 1+data_->tm_time_.tm_mon - << setw(2) << data_->tm_time_.tm_mday - << ' ' - << setw(2) << data_->tm_time_.tm_hour << ':' - << setw(2) << data_->tm_time_.tm_min << ':' - << setw(2) << data_->tm_time_.tm_sec << "." - << setw(6) << usecs - << ' ' - << setfill(' ') << setw(5) - << static_cast(GetTID()) << setfill('0') - << ' ' - << data_->basename_ << ':' << data_->line_ << "] "; - } - data_->num_prefix_chars_ = data_->stream_.pcount(); - - if (!FLAGS_log_backtrace_at.empty()) { - char fileline[128]; - snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line); -#ifdef HAVE_STACKTRACE - if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) { - string stacktrace; - DumpStackTraceToString(&stacktrace); - stream() << " (stacktrace:\n" << stacktrace << ") "; - } -#endif - } -} - -LogMessage::~LogMessage() { - Flush(); -#ifdef GLOG_THREAD_LOCAL_STORAGE - if (data_ == static_cast(&thread_msg_data)) { - data_->~LogMessageData(); - thread_data_available = true; - } - else { - delete allocated_; - } -#else // !defined(GLOG_THREAD_LOCAL_STORAGE) - delete allocated_; -#endif // defined(GLOG_THREAD_LOCAL_STORAGE) -} - -int LogMessage::preserved_errno() const { - return data_->preserved_errno_; -} - -ostream& LogMessage::stream() { - return data_->stream_; -} - -// Flush buffered message, called by the destructor, or any other function -// that needs to synchronize the log. -void LogMessage::Flush() { - if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel) - return; - - data_->num_chars_to_log_ = data_->stream_.pcount(); - data_->num_chars_to_syslog_ = - data_->num_chars_to_log_ - data_->num_prefix_chars_; - - // Do we need to add a \n to the end of this message? - bool append_newline = - (data_->message_text_[data_->num_chars_to_log_-1] != '\n'); - char original_final_char = '\0'; - - // If we do need to add a \n, we'll do it by violating the memory of the - // ostrstream buffer. This is quick, and we'll make sure to undo our - // modification before anything else is done with the ostrstream. It - // would be preferable not to do things this way, but it seems to be - // the best way to deal with this. - if (append_newline) { - original_final_char = data_->message_text_[data_->num_chars_to_log_]; - data_->message_text_[data_->num_chars_to_log_++] = '\n'; - } - - // Prevent any subtle race conditions by wrapping a mutex lock around - // the actual logging action per se. - { - MutexLock l(&log_mutex); - (this->*(data_->send_method_))(); - ++num_messages_[static_cast(data_->severity_)]; - } - LogDestination::WaitForSinks(data_); - - if (append_newline) { - // Fix the ostrstream back how it was before we screwed with it. - // It's 99.44% certain that we don't need to worry about doing this. - data_->message_text_[data_->num_chars_to_log_-1] = original_final_char; - } - - // If errno was already set before we enter the logging call, we'll - // set it back to that value when we return from the logging call. - // It happens often that we log an error message after a syscall - // failure, which can potentially set the errno to some other - // values. We would like to preserve the original errno. - if (data_->preserved_errno_ != 0) { - errno = data_->preserved_errno_; - } - - // Note that this message is now safely logged. If we're asked to flush - // again, as a result of destruction, say, we'll do nothing on future calls. - data_->has_been_flushed_ = true; -} - -// Copy of first FATAL log message so that we can print it out again -// after all the stack traces. To preserve legacy behavior, we don't -// use fatal_msg_data_exclusive. -static time_t fatal_time; -static char fatal_message[256]; - -void ReprintFatalMessage() { - if (fatal_message[0]) { - const int n = strlen(fatal_message); - if (!FLAGS_logtostderr) { - // Also write to stderr (don't color to avoid terminal checks) - WriteToStderr(fatal_message, n); - } - LogDestination::LogToAllLogfiles(GLOG_ERROR, fatal_time, fatal_message, n); - } -} - -// L >= log_mutex (callers must hold the log_mutex). -void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { - static bool already_warned_before_initgoogle = false; - - log_mutex.AssertHeld(); - - RAW_DCHECK(data_->num_chars_to_log_ > 0 && - data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); - - // Messages of a given severity get logged to lower severity logs, too - - if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) { - const char w[] = "WARNING: Logging before InitGoogleLogging() is " - "written to STDERR\n"; - WriteToStderr(w, strlen(w)); - already_warned_before_initgoogle = true; - } - - // global flag: never log to file if set. Also -- don't log to a - // file if we haven't parsed the command line flags to get the - // program name. - if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) { - ColoredWriteToStderr(data_->severity_, - data_->message_text_, data_->num_chars_to_log_); - - // this could be protected by a flag if necessary. - LogDestination::LogToSinks(data_->severity_, - data_->fullname_, data_->basename_, - data_->line_, &data_->tm_time_, - data_->message_text_ + data_->num_prefix_chars_, - (data_->num_chars_to_log_ - - data_->num_prefix_chars_ - 1)); - } else { - - // log this message to all log files of severity <= severity_ - LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_, - data_->message_text_, - data_->num_chars_to_log_); - - LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_, - data_->num_chars_to_log_); - LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_, - data_->num_chars_to_log_); - LogDestination::LogToSinks(data_->severity_, - data_->fullname_, data_->basename_, - data_->line_, &data_->tm_time_, - data_->message_text_ + data_->num_prefix_chars_, - (data_->num_chars_to_log_ - - data_->num_prefix_chars_ - 1)); - // NOTE: -1 removes trailing \n - } - - // If we log a FATAL message, flush all the log destinations, then toss - // a signal for others to catch. We leave the logs in a state that - // someone else can use them (as long as they flush afterwards) - if (data_->severity_ == GLOG_FATAL && exit_on_dfatal) { - if (data_->first_fatal_) { - // Store crash information so that it is accessible from within signal - // handlers that may be invoked later. - RecordCrashReason(&crash_reason); - SetCrashReason(&crash_reason); - - // Store shortened fatal message for other logs and GWQ status - const int copy = min(data_->num_chars_to_log_, - sizeof(fatal_message)-1); - memcpy(fatal_message, data_->message_text_, copy); - fatal_message[copy] = '\0'; - fatal_time = data_->timestamp_; - } - - if (!FLAGS_logtostderr) { - for (int i = 0; i < NUM_SEVERITIES; ++i) { - if ( LogDestination::log_destinations_[i] ) - LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0); - } - } - - // release the lock that our caller (directly or indirectly) - // LogMessage::~LogMessage() grabbed so that signal handlers - // can use the logging facility. Alternately, we could add - // an entire unsafe logging interface to bypass locking - // for signal handlers but this seems simpler. - log_mutex.Unlock(); - LogDestination::WaitForSinks(data_); - - const char* message = "*** Check failure stack trace: ***\n"; - if (write(STDERR_FILENO, message, strlen(message)) < 0) { - // Ignore errors. - } - Fail(); - } -} - -void LogMessage::RecordCrashReason( - glog_internal_namespace_::CrashReason* reason) { - reason->filename = fatal_msg_data_exclusive.fullname_; - reason->line_number = fatal_msg_data_exclusive.line_; - reason->message = fatal_msg_data_exclusive.message_text_ + - fatal_msg_data_exclusive.num_prefix_chars_; -#ifdef HAVE_STACKTRACE - // Retrieve the stack trace, omitting the logging frames that got us here. - reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4); -#else - reason->depth = 0; -#endif -} - -#ifdef HAVE___ATTRIBUTE__ -# define ATTRIBUTE_NORETURN __attribute__((noreturn)) -#else -# define ATTRIBUTE_NORETURN -#endif - -#if defined(OS_WINDOWS) -__declspec(noreturn) -#endif -static void logging_fail() ATTRIBUTE_NORETURN; - -static void logging_fail() { - abort(); -} - -typedef void (*logging_fail_func_t)() ATTRIBUTE_NORETURN; - -GOOGLE_GLOG_DLL_DECL -logging_fail_func_t g_logging_fail_func = &logging_fail; - -void InstallFailureFunction(void (*fail_func)()) { - g_logging_fail_func = (logging_fail_func_t)fail_func; -} - -void LogMessage::Fail() { - g_logging_fail_func(); -} - -// L >= log_mutex (callers must hold the log_mutex). -void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { - if (data_->sink_ != NULL) { - RAW_DCHECK(data_->num_chars_to_log_ > 0 && - data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); - data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_, - data_->line_, &data_->tm_time_, - data_->message_text_ + data_->num_prefix_chars_, - (data_->num_chars_to_log_ - - data_->num_prefix_chars_ - 1)); - } -} - -// L >= log_mutex (callers must hold the log_mutex). -void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { - SendToSink(); - SendToLog(); -} - -// L >= log_mutex (callers must hold the log_mutex). -void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { - if (data_->outvec_ != NULL) { - RAW_DCHECK(data_->num_chars_to_log_ > 0 && - data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); - // Omit prefix of message and trailing newline when recording in outvec_. - const char *start = data_->message_text_ + data_->num_prefix_chars_; - int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; - data_->outvec_->push_back(string(start, len)); - } else { - SendToLog(); - } -} - -void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { - if (data_->message_ != NULL) { - RAW_DCHECK(data_->num_chars_to_log_ > 0 && - data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); - // Omit prefix of message and trailing newline when writing to message_. - const char *start = data_->message_text_ + data_->num_prefix_chars_; - int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; - data_->message_->assign(start, len); - } - SendToLog(); -} - -// L >= log_mutex (callers must hold the log_mutex). -void LogMessage::SendToSyslogAndLog() { -#ifdef HAVE_SYSLOG_H - // Before any calls to syslog(), make a single call to openlog() - static bool openlog_already_called = false; - if (!openlog_already_called) { - openlog(glog_internal_namespace_::ProgramInvocationShortName(), - LOG_CONS | LOG_NDELAY | LOG_PID, - LOG_USER); - openlog_already_called = true; - } - - // This array maps Google severity levels to syslog levels - const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG }; - syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast(data_->severity_)], "%.*s", - int(data_->num_chars_to_syslog_), - data_->message_text_ + data_->num_prefix_chars_); - SendToLog(); -#else - LOG(ERROR) << "No syslog support: message=" << data_->message_text_; -#endif -} - -base::Logger* base::GetLogger(LogSeverity severity) { - MutexLock l(&log_mutex); - return LogDestination::log_destination(severity)->logger_; -} - -void base::SetLogger(LogSeverity severity, base::Logger* logger) { - MutexLock l(&log_mutex); - LogDestination::log_destination(severity)->logger_ = logger; -} - -// L < log_mutex. Acquires and releases mutex_. -int64 LogMessage::num_messages(int severity) { - MutexLock l(&log_mutex); - return num_messages_[severity]; -} - -// Output the COUNTER value. This is only valid if ostream is a -// LogStream. -ostream& operator<<(ostream &os, const PRIVATE_Counter&) { -#ifdef DISABLE_RTTI - LogMessage::LogStream *log = static_cast(&os); -#else - LogMessage::LogStream *log = dynamic_cast(&os); -#endif - CHECK(log && log == log->self()) - << "You must not use COUNTER with non-glog ostream"; - os << log->ctr(); - return os; -} - -ErrnoLogMessage::ErrnoLogMessage(const char* file, int line, - LogSeverity severity, int ctr, - void (LogMessage::*send_method)()) - : LogMessage(file, line, severity, ctr, send_method) { -} - -ErrnoLogMessage::~ErrnoLogMessage() { - // Don't access errno directly because it may have been altered - // while streaming the message. - stream() << ": " << StrError(preserved_errno()) << " [" - << preserved_errno() << "]"; -} - -void FlushLogFiles(LogSeverity min_severity) { - LogDestination::FlushLogFiles(min_severity); -} - -void FlushLogFilesUnsafe(LogSeverity min_severity) { - LogDestination::FlushLogFilesUnsafe(min_severity); -} - -void SetLogDestination(LogSeverity severity, const char* base_filename) { - LogDestination::SetLogDestination(severity, base_filename); -} - -void SetLogSymlink(LogSeverity severity, const char* symlink_basename) { - LogDestination::SetLogSymlink(severity, symlink_basename); -} - -LogSink::~LogSink() { -} - -void LogSink::WaitTillSent() { - // noop default -} - -string LogSink::ToString(LogSeverity severity, const char* file, int line, - const struct ::tm* tm_time, - const char* message, size_t message_len) { - ostringstream stream(string(message, message_len)); - stream.fill('0'); - - // FIXME(jrvb): Updating this to use the correct value for usecs - // requires changing the signature for both this method and - // LogSink::send(). This change needs to be done in a separate CL - // so subclasses of LogSink can be updated at the same time. - int usecs = 0; - - stream << LogSeverityNames[severity][0] - << setw(2) << 1+tm_time->tm_mon - << setw(2) << tm_time->tm_mday - << ' ' - << setw(2) << tm_time->tm_hour << ':' - << setw(2) << tm_time->tm_min << ':' - << setw(2) << tm_time->tm_sec << '.' - << setw(6) << usecs - << ' ' - << setfill(' ') << setw(5) << GetTID() << setfill('0') - << ' ' - << file << ':' << line << "] "; - - stream << string(message, message_len); - return stream.str(); -} - -void AddLogSink(LogSink *destination) { - LogDestination::AddLogSink(destination); -} - -void RemoveLogSink(LogSink *destination) { - LogDestination::RemoveLogSink(destination); -} - -void SetLogFilenameExtension(const char* ext) { - LogDestination::SetLogFilenameExtension(ext); -} - -void SetStderrLogging(LogSeverity min_severity) { - LogDestination::SetStderrLogging(min_severity); -} - -void SetEmailLogging(LogSeverity min_severity, const char* addresses) { - LogDestination::SetEmailLogging(min_severity, addresses); -} - -void LogToStderr() { - LogDestination::LogToStderr(); -} - -namespace base { -namespace internal { - -bool GetExitOnDFatal(); -bool GetExitOnDFatal() { - MutexLock l(&log_mutex); - return exit_on_dfatal; -} - -// Determines whether we exit the program for a LOG(DFATAL) message in -// debug mode. It does this by skipping the call to Fail/FailQuietly. -// This is intended for testing only. -// -// This can have some effects on LOG(FATAL) as well. Failure messages -// are always allocated (rather than sharing a buffer), the crash -// reason is not recorded, the "gwq" status message is not updated, -// and the stack trace is not recorded. The LOG(FATAL) *will* still -// exit the program. Since this function is used only in testing, -// these differences are acceptable. -void SetExitOnDFatal(bool value); -void SetExitOnDFatal(bool value) { - MutexLock l(&log_mutex); - exit_on_dfatal = value; -} - -} // namespace internal -} // namespace base - -// Shell-escaping as we need to shell out ot /bin/mail. -static const char kDontNeedShellEscapeChars[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+-_.=/:,@"; - -static string ShellEscape(const string& src) { - string result; - if (!src.empty() && // empty string needs quotes - src.find_first_not_of(kDontNeedShellEscapeChars) == string::npos) { - // only contains chars that don't need quotes; it's fine - result.assign(src); - } else if (src.find_first_of('\'') == string::npos) { - // no single quotes; just wrap it in single quotes - result.assign("'"); - result.append(src); - result.append("'"); - } else { - // needs double quote escaping - result.assign("\""); - for (size_t i = 0; i < src.size(); ++i) { - switch (src[i]) { - case '\\': - case '$': - case '"': - case '`': - result.append("\\"); - } - result.append(src, i, 1); - } - result.append("\""); - } - return result; -} - - -// use_logging controls whether the logging functions LOG/VLOG are used -// to log errors. It should be set to false when the caller holds the -// log_mutex. -static bool SendEmailInternal(const char*dest, const char *subject, - const char*body, bool use_logging) { - if (dest && *dest) { - if ( use_logging ) { - VLOG(1) << "Trying to send TITLE:" << subject - << " BODY:" << body << " to " << dest; - } else { - fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n", - subject, body, dest); - } - - string cmd = - FLAGS_logmailer + " -s" + - ShellEscape(subject) + " " + ShellEscape(dest); - VLOG(4) << "Mailing command: " << cmd; - - FILE* pipe = popen(cmd.c_str(), "w"); - if (pipe != NULL) { - // Add the body if we have one - if (body) - fwrite(body, sizeof(char), strlen(body), pipe); - bool ok = pclose(pipe) != -1; - if ( !ok ) { - if ( use_logging ) { - LOG(ERROR) << "Problems sending mail to " << dest << ": " - << StrError(errno); - } else { - fprintf(stderr, "Problems sending mail to %s: %s\n", - dest, StrError(errno).c_str()); - } - } - return ok; - } else { - if ( use_logging ) { - LOG(ERROR) << "Unable to send mail to " << dest; - } else { - fprintf(stderr, "Unable to send mail to %s\n", dest); - } - } - } - return false; -} - -bool SendEmail(const char*dest, const char *subject, const char*body){ - return SendEmailInternal(dest, subject, body, true); -} - -static void GetTempDirectories(vector* list) { - list->clear(); -#ifdef OS_WINDOWS - // On windows we'll try to find a directory in this order: - // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is) - // C:/TMP/ - // C:/TEMP/ - // C:/WINDOWS/ or C:/WINNT/ - // . - char tmp[MAX_PATH]; - if (GetTempPathA(MAX_PATH, tmp)) - list->push_back(tmp); - list->push_back("C:\\tmp\\"); - list->push_back("C:\\temp\\"); -#else - // Directories, in order of preference. If we find a dir that - // exists, we stop adding other less-preferred dirs - const char * candidates[] = { - // Non-null only during unittest/regtest - getenv("TEST_TMPDIR"), - - // Explicitly-supplied temp dirs - getenv("TMPDIR"), getenv("TMP"), - - // If all else fails - "/tmp", - }; - - for (size_t i = 0; i < ARRAYSIZE(candidates); i++) { - const char *d = candidates[i]; - if (!d) continue; // Empty env var - - // Make sure we don't surprise anyone who's expecting a '/' - string dstr = d; - if (dstr[dstr.size() - 1] != '/') { - dstr += "/"; - } - list->push_back(dstr); - - struct stat statbuf; - if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) { - // We found a dir that exists - we're done. - return; - } - } - -#endif -} - -static vector* logging_directories_list; - -const vector& GetLoggingDirectories() { - // Not strictly thread-safe but we're called early in InitGoogle(). - if (logging_directories_list == NULL) { - logging_directories_list = new vector; - - if ( !FLAGS_log_dir.empty() ) { - // A dir was specified, we should use it - logging_directories_list->push_back(FLAGS_log_dir.c_str()); - } else { - GetTempDirectories(logging_directories_list); -#ifdef OS_WINDOWS - char tmp[MAX_PATH]; - if (GetWindowsDirectoryA(tmp, MAX_PATH)) - logging_directories_list->push_back(tmp); - logging_directories_list->push_back(".\\"); -#else - logging_directories_list->push_back("./"); -#endif - } - } - return *logging_directories_list; -} - -void TestOnly_ClearLoggingDirectoriesList() { - fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be " - "called from test code.\n"); - delete logging_directories_list; - logging_directories_list = NULL; -} - -void GetExistingTempDirectories(vector* list) { - GetTempDirectories(list); - vector::iterator i_dir = list->begin(); - while( i_dir != list->end() ) { - // zero arg to access means test for existence; no constant - // defined on windows - if ( access(i_dir->c_str(), 0) ) { - i_dir = list->erase(i_dir); - } else { - ++i_dir; - } - } -} - -void TruncateLogFile(const char *path, int64 limit, int64 keep) { -#ifdef HAVE_UNISTD_H - struct stat statbuf; - const int kCopyBlockSize = 8 << 10; - char copybuf[kCopyBlockSize]; - int64 read_offset, write_offset; - // Don't follow symlinks unless they're our own fd symlinks in /proc - int flags = O_RDWR; - // TODO(hamaji): Support other environments. -#ifdef OS_LINUX - const char *procfd_prefix = "/proc/self/fd/"; - if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW; -#endif - - int fd = open(path, flags); - if (fd == -1) { - if (errno == EFBIG) { - // The log file in question has got too big for us to open. The - // real fix for this would be to compile logging.cc (or probably - // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's - // rather scary. - // Instead just truncate the file to something we can manage - if (truncate(path, 0) == -1) { - PLOG(ERROR) << "Unable to truncate " << path; - } else { - LOG(ERROR) << "Truncated " << path << " due to EFBIG error"; - } - } else { - PLOG(ERROR) << "Unable to open " << path; - } - return; - } - - if (fstat(fd, &statbuf) == -1) { - PLOG(ERROR) << "Unable to fstat()"; - goto out_close_fd; - } - - // See if the path refers to a regular file bigger than the - // specified limit - if (!S_ISREG(statbuf.st_mode)) goto out_close_fd; - if (statbuf.st_size <= limit) goto out_close_fd; - if (statbuf.st_size <= keep) goto out_close_fd; - - // This log file is too large - we need to truncate it - LOG(INFO) << "Truncating " << path << " to " << keep << " bytes"; - - // Copy the last "keep" bytes of the file to the beginning of the file - read_offset = statbuf.st_size - keep; - write_offset = 0; - int bytesin, bytesout; - while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) { - bytesout = pwrite(fd, copybuf, bytesin, write_offset); - if (bytesout == -1) { - PLOG(ERROR) << "Unable to write to " << path; - break; - } else if (bytesout != bytesin) { - LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout; - } - read_offset += bytesin; - write_offset += bytesout; - } - if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path; - - // Truncate the remainder of the file. If someone else writes to the - // end of the file after our last read() above, we lose their latest - // data. Too bad ... - if (ftruncate(fd, write_offset) == -1) { - PLOG(ERROR) << "Unable to truncate " << path; - } - - out_close_fd: - close(fd); -#else - LOG(ERROR) << "No log truncation support."; -#endif -} - -void TruncateStdoutStderr() { -#ifdef HAVE_UNISTD_H - int64 limit = MaxLogSize() << 20; - int64 keep = 1 << 20; - TruncateLogFile("/proc/self/fd/1", limit, keep); - TruncateLogFile("/proc/self/fd/2", limit, keep); -#else - LOG(ERROR) << "No log truncation support."; -#endif -} - - -// Helper functions for string comparisons. -#define DEFINE_CHECK_STROP_IMPL(name, func, expected) \ - string* Check##func##expected##Impl(const char* s1, const char* s2, \ - const char* names) { \ - bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \ - if (equal == expected) return NULL; \ - else { \ - ostringstream ss; \ - if (!s1) s1 = ""; \ - if (!s2) s2 = ""; \ - ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \ - return new string(ss.str()); \ - } \ - } -DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true) -DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false) -DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true) -DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false) -#undef DEFINE_CHECK_STROP_IMPL - -int posix_strerror_r(int err, char *buf, size_t len) { - // Sanity check input parameters - if (buf == NULL || len <= 0) { - errno = EINVAL; - return -1; - } - - // Reset buf and errno, and try calling whatever version of strerror_r() - // is implemented by glibc - buf[0] = '\000'; - int old_errno = errno; - errno = 0; - char *rc = reinterpret_cast(strerror_r(err, buf, len)); - - // Both versions set errno on failure - if (errno) { - // Should already be there, but better safe than sorry - buf[0] = '\000'; - return -1; - } - errno = old_errno; - - // POSIX is vague about whether the string will be terminated, although - // is indirectly implies that typically ERANGE will be returned, instead - // of truncating the string. This is different from the GNU implementation. - // We play it safe by always terminating the string explicitly. - buf[len-1] = '\000'; - - // If the function succeeded, we can use its exit code to determine the - // semantics implemented by glibc - if (!rc) { - return 0; - } else { - // GNU semantics detected - if (rc == buf) { - return 0; - } else { - buf[0] = '\000'; -#if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD) - if (reinterpret_cast(rc) < sys_nerr) { - // This means an error on MacOSX or FreeBSD. - return -1; - } -#endif - strncat(buf, rc, len-1); - return 0; - } - } -} - -string StrError(int err) { - char buf[100]; - int rc = posix_strerror_r(err, buf, sizeof(buf)); - if ((rc < 0) || (buf[0] == '\000')) { - snprintf(buf, sizeof(buf), "Error number %d", err); - } - return buf; -} - -LogMessageFatal::LogMessageFatal(const char* file, int line) : - LogMessage(file, line, GLOG_FATAL) {} - -LogMessageFatal::LogMessageFatal(const char* file, int line, - const CheckOpString& result) : - LogMessage(file, line, result) {} - -LogMessageFatal::~LogMessageFatal() { - Flush(); - LogMessage::Fail(); -} - -namespace base { - -CheckOpMessageBuilder::CheckOpMessageBuilder(const char *exprtext) - : stream_(new ostringstream) { - *stream_ << exprtext << " ("; -} - -CheckOpMessageBuilder::~CheckOpMessageBuilder() { - delete stream_; -} - -ostream* CheckOpMessageBuilder::ForVar2() { - *stream_ << " vs. "; - return stream_; -} - -string* CheckOpMessageBuilder::NewString() { - *stream_ << ")"; - return new string(stream_->str()); -} - -} // namespace base - -template <> -void MakeCheckOpValueString(std::ostream* os, const char& v) { - if (v >= 32 && v <= 126) { - (*os) << "'" << v << "'"; - } else { - (*os) << "char value " << (short)v; - } -} - -template <> -void MakeCheckOpValueString(std::ostream* os, const signed char& v) { - if (v >= 32 && v <= 126) { - (*os) << "'" << v << "'"; - } else { - (*os) << "signed char value " << (short)v; - } -} - -template <> -void MakeCheckOpValueString(std::ostream* os, const unsigned char& v) { - if (v >= 32 && v <= 126) { - (*os) << "'" << v << "'"; - } else { - (*os) << "unsigned char value " << (unsigned short)v; - } -} - -void InitGoogleLogging(const char* argv0) { - glog_internal_namespace_::InitGoogleLoggingUtilities(argv0); -} - -void ShutdownGoogleLogging() { - glog_internal_namespace_::ShutdownGoogleLoggingUtilities(); - LogDestination::DeleteLogDestinations(); - delete logging_directories_list; - logging_directories_list = NULL; -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striplog_test.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striplog_test.sh deleted file mode 100755 index 73492bda7a7..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striplog_test.sh +++ /dev/null @@ -1,79 +0,0 @@ -#! /bin/sh -# -# Copyright (c) 2007, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# Author: Sergey Ioffe - -get_strings () { - if test -e ".libs/$1"; then - binary=".libs/$1" - elif test -e "$1.exe"; then - binary="$1.exe" - else - echo "We coundn't find $1 binary." - exit 1 - fi - - strings -n 10 $binary | sort | awk '/TESTMESSAGE/ {printf "%s ", $2}' -} - -# Die if "$1" != "$2", print $3 as death reason -check_eq () { - if [ "$1" != "$2" ]; then - echo "Check failed: '$1' == '$2' ${3:+ ($3)}" - exit 1 - fi -} - -die () { - echo $1 - exit 1 -} - -# Check that the string literals are appropriately stripped. This will -# not be the case in debug mode. - -mode=`GLOG_check_mode=1 ./logging_striptest0 2> /dev/null` -if [ "$mode" = "opt" ]; -then - echo "In OPT mode" - check_eq "`get_strings logging_striptest0`" "COND ERROR FATAL INFO USAGE WARNING " - check_eq "`get_strings logging_striptest2`" "COND ERROR FATAL USAGE " - check_eq "`get_strings logging_striptest10`" "" -else - echo "In DBG mode; not checking strings" -fi - -# Check that LOG(FATAL) aborts even for large STRIP_LOG - -./logging_striptest2 2>/dev/null && die "Did not abort for STRIP_LOG=2" -./logging_striptest10 2>/dev/null && die "Did not abort for STRIP_LOG=10" - -echo "PASS" diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striptest10.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striptest10.cc deleted file mode 100644 index f6e1078f39a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striptest10.cc +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Sergey Ioffe - -#define GOOGLE_STRIP_LOG 10 - -// Include the actual test. -#include "logging_striptest_main.cc" diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striptest2.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striptest2.cc deleted file mode 100644 index a64685c9e5c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striptest2.cc +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Sergey Ioffe - -#define GOOGLE_STRIP_LOG 2 - -// Include the actual test. -#include "logging_striptest_main.cc" diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striptest_main.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striptest_main.cc deleted file mode 100644 index 2fb91272a7b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_striptest_main.cc +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Sergey Ioffe - -// The common part of the striplog tests. - -#include -#include -#include -#include "glog/logging.h" -#include "base/commandlineflags.h" -#include "config.h" - -DECLARE_bool(logtostderr); -GLOG_DEFINE_bool(check_mode, false, "Prints 'opt' or 'dbg'"); - -using std::string; -using namespace GOOGLE_NAMESPACE; - -int CheckNoReturn(bool b) { - string s; - if (b) { - LOG(FATAL) << "Fatal"; - } else { - return 0; - } -} - -struct A { }; -std::ostream &operator<<(std::ostream &str, const A&) {return str;} - -int main(int, char* argv[]) { - FLAGS_logtostderr = true; - InitGoogleLogging(argv[0]); - if (FLAGS_check_mode) { - printf("%s\n", DEBUG_MODE ? "dbg" : "opt"); - return 0; - } - LOG(INFO) << "TESTMESSAGE INFO"; - LOG(WARNING) << 2 << "something" << "TESTMESSAGE WARNING" - << 1 << 'c' << A() << std::endl; - LOG(ERROR) << "TESTMESSAGE ERROR"; - bool flag = true; - (flag ? LOG(INFO) : LOG(ERROR)) << "TESTMESSAGE COND"; - LOG(FATAL) << "TESTMESSAGE FATAL"; -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_unittest.cc deleted file mode 100644 index 762c752d971..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_unittest.cc +++ /dev/null @@ -1,1227 +0,0 @@ -// Copyright (c) 2002, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Ray Sidney - -#include "config_for_unittests.h" -#include "utilities.h" - -#include -#ifdef HAVE_GLOB_H -# include -#endif -#include -#ifdef HAVE_UNISTD_H -# include -#endif - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "base/commandlineflags.h" -#include "glog/logging.h" -#include "glog/raw_logging.h" -#include "googletest.h" - -DECLARE_string(log_backtrace_at); // logging.cc - -#ifdef HAVE_LIB_GFLAGS -#include -using namespace GFLAGS_NAMESPACE; -#endif - -#ifdef HAVE_LIB_GMOCK -#include -#include "mock-log.h" -// Introduce several symbols from gmock. -using testing::_; -using testing::AnyNumber; -using testing::HasSubstr; -using testing::AllOf; -using testing::StrNe; -using testing::StrictMock; -using testing::InitGoogleMock; -using GOOGLE_NAMESPACE::glog_testing::ScopedMockLog; -#endif - -using namespace std; -using namespace GOOGLE_NAMESPACE; - -// Some non-advertised functions that we want to test or use. -_START_GOOGLE_NAMESPACE_ -namespace base { -namespace internal { -bool GetExitOnDFatal(); -void SetExitOnDFatal(bool value); -} // namespace internal -} // namespace base -_END_GOOGLE_NAMESPACE_ - -static void TestLogging(bool check_counts); -static void TestRawLogging(); -static void LogWithLevels(int v, int severity, bool err, bool alsoerr); -static void TestLoggingLevels(); -static void TestLogString(); -static void TestLogSink(); -static void TestLogToString(); -static void TestLogSinkWaitTillSent(); -static void TestCHECK(); -static void TestDCHECK(); -static void TestSTREQ(); -static void TestBasename(); -static void TestSymlink(); -static void TestExtension(); -static void TestWrapper(); -static void TestErrno(); -static void TestTruncate(); - -static int x = -1; -static void BM_Check1(int n) { - while (n-- > 0) { - CHECK_GE(n, x); - CHECK_GE(n, x); - CHECK_GE(n, x); - CHECK_GE(n, x); - CHECK_GE(n, x); - CHECK_GE(n, x); - CHECK_GE(n, x); - CHECK_GE(n, x); - } -} -BENCHMARK(BM_Check1); - -static void CheckFailure(int a, int b, const char* file, int line, const char* msg); -static void BM_Check3(int n) { - while (n-- > 0) { - if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); - if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); - if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); - if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); - if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); - if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); - if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); - if (n < x) CheckFailure(n, x, __FILE__, __LINE__, "n < x"); - } -} -BENCHMARK(BM_Check3); - -static void BM_Check2(int n) { - if (n == 17) { - x = 5; - } - while (n-- > 0) { - CHECK(n >= x); - CHECK(n >= x); - CHECK(n >= x); - CHECK(n >= x); - CHECK(n >= x); - CHECK(n >= x); - CHECK(n >= x); - CHECK(n >= x); - } -} -BENCHMARK(BM_Check2); - -static void CheckFailure(int, int, const char* /* file */, int /* line */, - const char* /* msg */) { -} - -static void BM_logspeed(int n) { - while (n-- > 0) { - LOG(INFO) << "test message"; - } -} -BENCHMARK(BM_logspeed); - -static void BM_vlog(int n) { - while (n-- > 0) { - VLOG(1) << "test message"; - } -} -BENCHMARK(BM_vlog); - -int main(int argc, char **argv) { - FLAGS_colorlogtostderr = false; -#ifdef HAVE_LIB_GFLAGS - ParseCommandLineFlags(&argc, &argv, true); -#endif - // Make sure stderr is not buffered as stderr seems to be buffered - // on recent windows. - setbuf(stderr, NULL); - - // Test some basics before InitGoogleLogging: - CaptureTestStderr(); - LogWithLevels(FLAGS_v, FLAGS_stderrthreshold, - FLAGS_logtostderr, FLAGS_alsologtostderr); - LogWithLevels(0, 0, 0, 0); // simulate "before global c-tors" - const string early_stderr = GetCapturedTestStderr(); - - InitGoogleLogging(argv[0]); - - RunSpecifiedBenchmarks(); - - FLAGS_logtostderr = true; - - InitGoogleTest(&argc, argv); -#ifdef HAVE_LIB_GMOCK - InitGoogleMock(&argc, argv); -#endif - - // so that death tests run before we use threads - CHECK_EQ(RUN_ALL_TESTS(), 0); - - CaptureTestStderr(); - - // re-emit early_stderr - LogMessage("dummy", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << early_stderr; - - TestLogging(true); - TestRawLogging(); - TestLoggingLevels(); - TestLogString(); - TestLogSink(); - TestLogToString(); - TestLogSinkWaitTillSent(); - TestCHECK(); - TestDCHECK(); - TestSTREQ(); - - // TODO: The golden test portion of this test is very flakey. - EXPECT_TRUE( - MungeAndDiffTestStderr(FLAGS_test_srcdir + "/src/logging_unittest.err")); - - FLAGS_logtostderr = false; - - TestBasename(); - TestSymlink(); - TestExtension(); - TestWrapper(); - TestErrno(); - TestTruncate(); - - ShutdownGoogleLogging(); - - fprintf(stdout, "PASS\n"); - return 0; -} - -void TestLogging(bool check_counts) { - int64 base_num_infos = LogMessage::num_messages(GLOG_INFO); - int64 base_num_warning = LogMessage::num_messages(GLOG_WARNING); - int64 base_num_errors = LogMessage::num_messages(GLOG_ERROR); - - LOG(INFO) << string("foo ") << "bar " << 10 << ' ' << 3.4; - for ( int i = 0; i < 10; ++i ) { - int old_errno = errno; - errno = i; - PLOG_EVERY_N(ERROR, 2) << "Plog every 2, iteration " << COUNTER; - errno = old_errno; - - LOG_EVERY_N(ERROR, 3) << "Log every 3, iteration " << COUNTER << endl; - LOG_EVERY_N(ERROR, 4) << "Log every 4, iteration " << COUNTER << endl; - - LOG_IF_EVERY_N(WARNING, true, 5) << "Log if every 5, iteration " << COUNTER; - LOG_IF_EVERY_N(WARNING, false, 3) - << "Log if every 3, iteration " << COUNTER; - LOG_IF_EVERY_N(INFO, true, 1) << "Log if every 1, iteration " << COUNTER; - LOG_IF_EVERY_N(ERROR, (i < 3), 2) - << "Log if less than 3 every 2, iteration " << COUNTER; - } - LOG_IF(WARNING, true) << "log_if this"; - LOG_IF(WARNING, false) << "don't log_if this"; - - char s[] = "array"; - LOG(INFO) << s; - const char const_s[] = "const array"; - LOG(INFO) << const_s; - int j = 1000; - LOG(ERROR) << string("foo") << ' '<< j << ' ' << setw(10) << j << " " - << setw(1) << hex << j; - - { - google::LogMessage outer(__FILE__, __LINE__, GLOG_ERROR); - outer.stream() << "outer"; - - LOG(ERROR) << "inner"; - } - - LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() << "no prefix"; - - if (check_counts) { - CHECK_EQ(base_num_infos + 14, LogMessage::num_messages(GLOG_INFO)); - CHECK_EQ(base_num_warning + 3, LogMessage::num_messages(GLOG_WARNING)); - CHECK_EQ(base_num_errors + 17, LogMessage::num_messages(GLOG_ERROR)); - } -} - -static void NoAllocNewHook() { - LOG(FATAL) << "unexpected new"; -} - -struct NewHook { - NewHook() { - g_new_hook = &NoAllocNewHook; - } - ~NewHook() { - g_new_hook = NULL; - } -}; - -TEST(DeathNoAllocNewHook, logging) { - // tests that NewHook used below works - NewHook new_hook; - ASSERT_DEATH({ - new int; - }, "unexpected new"); -} - -void TestRawLogging() { - string* foo = new string("foo "); - string huge_str(50000, 'a'); - - FlagSaver saver; - - // Check that RAW loggging does not use mallocs. - NewHook new_hook; - - RAW_LOG(INFO, "%s%s%d%c%f", foo->c_str(), "bar ", 10, ' ', 3.4); - char s[] = "array"; - RAW_LOG(WARNING, "%s", s); - const char const_s[] = "const array"; - RAW_LOG(INFO, "%s", const_s); - void* p = reinterpret_cast(PTR_TEST_VALUE); - RAW_LOG(INFO, "ptr %p", p); - p = NULL; - RAW_LOG(INFO, "ptr %p", p); - int j = 1000; - RAW_LOG(ERROR, "%s%d%c%010d%s%1x", foo->c_str(), j, ' ', j, " ", j); - RAW_VLOG(0, "foo %d", j); - -#ifdef NDEBUG - RAW_LOG(INFO, "foo %d", j); // so that have same stderr to compare -#else - RAW_DLOG(INFO, "foo %d", j); // test RAW_DLOG in debug mode -#endif - - // test how long messages are chopped: - RAW_LOG(WARNING, "Huge string: %s", huge_str.c_str()); - RAW_VLOG(0, "Huge string: %s", huge_str.c_str()); - - FLAGS_v = 0; - RAW_LOG(INFO, "log"); - RAW_VLOG(0, "vlog 0 on"); - RAW_VLOG(1, "vlog 1 off"); - RAW_VLOG(2, "vlog 2 off"); - RAW_VLOG(3, "vlog 3 off"); - FLAGS_v = 2; - RAW_LOG(INFO, "log"); - RAW_VLOG(1, "vlog 1 on"); - RAW_VLOG(2, "vlog 2 on"); - RAW_VLOG(3, "vlog 3 off"); - -#ifdef NDEBUG - RAW_DCHECK(1 == 2, " RAW_DCHECK's shouldn't be compiled in normal mode"); -#endif - - RAW_CHECK(1 == 1, "should be ok"); - RAW_DCHECK(true, "should be ok"); - - delete foo; -} - -void LogWithLevels(int v, int severity, bool err, bool alsoerr) { - RAW_LOG(INFO, - "Test: v=%d stderrthreshold=%d logtostderr=%d alsologtostderr=%d", - v, severity, err, alsoerr); - - FlagSaver saver; - - FLAGS_v = v; - FLAGS_stderrthreshold = severity; - FLAGS_logtostderr = err; - FLAGS_alsologtostderr = alsoerr; - - RAW_VLOG(-1, "vlog -1"); - RAW_VLOG(0, "vlog 0"); - RAW_VLOG(1, "vlog 1"); - RAW_LOG(INFO, "log info"); - RAW_LOG(WARNING, "log warning"); - RAW_LOG(ERROR, "log error"); - - VLOG(-1) << "vlog -1"; - VLOG(0) << "vlog 0"; - VLOG(1) << "vlog 1"; - LOG(INFO) << "log info"; - LOG(WARNING) << "log warning"; - LOG(ERROR) << "log error"; - - VLOG_IF(-1, true) << "vlog_if -1"; - VLOG_IF(-1, false) << "don't vlog_if -1"; - VLOG_IF(0, true) << "vlog_if 0"; - VLOG_IF(0, false) << "don't vlog_if 0"; - VLOG_IF(1, true) << "vlog_if 1"; - VLOG_IF(1, false) << "don't vlog_if 1"; - LOG_IF(INFO, true) << "log_if info"; - LOG_IF(INFO, false) << "don't log_if info"; - LOG_IF(WARNING, true) << "log_if warning"; - LOG_IF(WARNING, false) << "don't log_if warning"; - LOG_IF(ERROR, true) << "log_if error"; - LOG_IF(ERROR, false) << "don't log_if error"; - - int c; - c = 1; VLOG_IF(100, c -= 2) << "vlog_if 100 expr"; EXPECT_EQ(c, -1); - c = 1; VLOG_IF(0, c -= 2) << "vlog_if 0 expr"; EXPECT_EQ(c, -1); - c = 1; LOG_IF(INFO, c -= 2) << "log_if info expr"; EXPECT_EQ(c, -1); - c = 1; LOG_IF(ERROR, c -= 2) << "log_if error expr"; EXPECT_EQ(c, -1); - c = 2; VLOG_IF(0, c -= 2) << "don't vlog_if 0 expr"; EXPECT_EQ(c, 0); - c = 2; LOG_IF(ERROR, c -= 2) << "don't log_if error expr"; EXPECT_EQ(c, 0); - - c = 3; LOG_IF_EVERY_N(INFO, c -= 4, 1) << "log_if info every 1 expr"; - EXPECT_EQ(c, -1); - c = 3; LOG_IF_EVERY_N(ERROR, c -= 4, 1) << "log_if error every 1 expr"; - EXPECT_EQ(c, -1); - c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if info every 3 expr"; - EXPECT_EQ(c, 0); - c = 4; LOG_IF_EVERY_N(ERROR, c -= 4, 3) << "don't log_if error every 3 expr"; - EXPECT_EQ(c, 0); - c = 5; VLOG_IF_EVERY_N(0, c -= 4, 1) << "vlog_if 0 every 1 expr"; - EXPECT_EQ(c, 1); - c = 5; VLOG_IF_EVERY_N(100, c -= 4, 3) << "vlog_if 100 every 3 expr"; - EXPECT_EQ(c, 1); - c = 6; VLOG_IF_EVERY_N(0, c -= 6, 1) << "don't vlog_if 0 every 1 expr"; - EXPECT_EQ(c, 0); - c = 6; VLOG_IF_EVERY_N(100, c -= 6, 3) << "don't vlog_if 100 every 1 expr"; - EXPECT_EQ(c, 0); -} - -void TestLoggingLevels() { - LogWithLevels(0, GLOG_INFO, false, false); - LogWithLevels(1, GLOG_INFO, false, false); - LogWithLevels(-1, GLOG_INFO, false, false); - LogWithLevels(0, GLOG_WARNING, false, false); - LogWithLevels(0, GLOG_ERROR, false, false); - LogWithLevels(0, GLOG_FATAL, false, false); - LogWithLevels(0, GLOG_FATAL, true, false); - LogWithLevels(0, GLOG_FATAL, false, true); - LogWithLevels(1, GLOG_WARNING, false, false); - LogWithLevels(1, GLOG_FATAL, false, true); -} - -TEST(DeathRawCHECK, logging) { - ASSERT_DEATH(RAW_CHECK(false, "failure 1"), - "RAW: Check false failed: failure 1"); - ASSERT_DEBUG_DEATH(RAW_DCHECK(1 == 2, "failure 2"), - "RAW: Check 1 == 2 failed: failure 2"); -} - -void TestLogString() { - vector errors; - vector *no_errors = NULL; - - LOG_STRING(INFO, &errors) << "LOG_STRING: " << "collected info"; - LOG_STRING(WARNING, &errors) << "LOG_STRING: " << "collected warning"; - LOG_STRING(ERROR, &errors) << "LOG_STRING: " << "collected error"; - - LOG_STRING(INFO, no_errors) << "LOG_STRING: " << "reported info"; - LOG_STRING(WARNING, no_errors) << "LOG_STRING: " << "reported warning"; - LOG_STRING(ERROR, NULL) << "LOG_STRING: " << "reported error"; - - for (size_t i = 0; i < errors.size(); ++i) { - LOG(INFO) << "Captured by LOG_STRING: " << errors[i]; - } -} - -void TestLogToString() { - string error; - string* no_error = NULL; - - LOG_TO_STRING(INFO, &error) << "LOG_TO_STRING: " << "collected info"; - LOG(INFO) << "Captured by LOG_TO_STRING: " << error; - LOG_TO_STRING(WARNING, &error) << "LOG_TO_STRING: " << "collected warning"; - LOG(INFO) << "Captured by LOG_TO_STRING: " << error; - LOG_TO_STRING(ERROR, &error) << "LOG_TO_STRING: " << "collected error"; - LOG(INFO) << "Captured by LOG_TO_STRING: " << error; - - LOG_TO_STRING(INFO, no_error) << "LOG_TO_STRING: " << "reported info"; - LOG_TO_STRING(WARNING, no_error) << "LOG_TO_STRING: " << "reported warning"; - LOG_TO_STRING(ERROR, NULL) << "LOG_TO_STRING: " << "reported error"; -} - -class TestLogSinkImpl : public LogSink { - public: - vector errors; - virtual void send(LogSeverity severity, const char* /* full_filename */, - const char* base_filename, int line, - const struct tm* tm_time, - const char* message, size_t message_len) { - errors.push_back( - ToString(severity, base_filename, line, tm_time, message, message_len)); - } -}; - -void TestLogSink() { - TestLogSinkImpl sink; - LogSink *no_sink = NULL; - - LOG_TO_SINK(&sink, INFO) << "LOG_TO_SINK: " << "collected info"; - LOG_TO_SINK(&sink, WARNING) << "LOG_TO_SINK: " << "collected warning"; - LOG_TO_SINK(&sink, ERROR) << "LOG_TO_SINK: " << "collected error"; - - LOG_TO_SINK(no_sink, INFO) << "LOG_TO_SINK: " << "reported info"; - LOG_TO_SINK(no_sink, WARNING) << "LOG_TO_SINK: " << "reported warning"; - LOG_TO_SINK(NULL, ERROR) << "LOG_TO_SINK: " << "reported error"; - - LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, INFO) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected info"; - LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, WARNING) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected warning"; - LOG_TO_SINK_BUT_NOT_TO_LOGFILE(&sink, ERROR) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "collected error"; - - LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, INFO) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed info"; - LOG_TO_SINK_BUT_NOT_TO_LOGFILE(no_sink, WARNING) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed warning"; - LOG_TO_SINK_BUT_NOT_TO_LOGFILE(NULL, ERROR) - << "LOG_TO_SINK_BUT_NOT_TO_LOGFILE: " << "thrashed error"; - - LOG(INFO) << "Captured by LOG_TO_SINK:"; - for (size_t i = 0; i < sink.errors.size(); ++i) { - LogMessage("foo", LogMessage::kNoLogPrefix, GLOG_INFO).stream() - << sink.errors[i]; - } -} - -// For testing using CHECK*() on anonymous enums. -enum { - CASE_A, - CASE_B -}; - -void TestCHECK() { - // Tests using CHECK*() on int values. - CHECK(1 == 1); - CHECK_EQ(1, 1); - CHECK_NE(1, 2); - CHECK_GE(1, 1); - CHECK_GE(2, 1); - CHECK_LE(1, 1); - CHECK_LE(1, 2); - CHECK_GT(2, 1); - CHECK_LT(1, 2); - - // Tests using CHECK*() on anonymous enums. - // Apple's GCC doesn't like this. -#if !defined(OS_MACOSX) - CHECK_EQ(CASE_A, CASE_A); - CHECK_NE(CASE_A, CASE_B); - CHECK_GE(CASE_A, CASE_A); - CHECK_GE(CASE_B, CASE_A); - CHECK_LE(CASE_A, CASE_A); - CHECK_LE(CASE_A, CASE_B); - CHECK_GT(CASE_B, CASE_A); - CHECK_LT(CASE_A, CASE_B); -#endif -} - -void TestDCHECK() { -#ifdef NDEBUG - DCHECK( 1 == 2 ) << " DCHECK's shouldn't be compiled in normal mode"; -#endif - DCHECK( 1 == 1 ); - DCHECK_EQ(1, 1); - DCHECK_NE(1, 2); - DCHECK_GE(1, 1); - DCHECK_GE(2, 1); - DCHECK_LE(1, 1); - DCHECK_LE(1, 2); - DCHECK_GT(2, 1); - DCHECK_LT(1, 2); - - int64* orig_ptr = new int64; - int64* ptr = DCHECK_NOTNULL(orig_ptr); - CHECK_EQ(ptr, orig_ptr); - delete orig_ptr; -} - -void TestSTREQ() { - CHECK_STREQ("this", "this"); - CHECK_STREQ(NULL, NULL); - CHECK_STRCASEEQ("this", "tHiS"); - CHECK_STRCASEEQ(NULL, NULL); - CHECK_STRNE("this", "tHiS"); - CHECK_STRNE("this", NULL); - CHECK_STRCASENE("this", "that"); - CHECK_STRCASENE(NULL, "that"); - CHECK_STREQ((string("a")+"b").c_str(), "ab"); - CHECK_STREQ(string("test").c_str(), - (string("te") + string("st")).c_str()); -} - -TEST(DeathSTREQ, logging) { - ASSERT_DEATH(CHECK_STREQ(NULL, "this"), ""); - ASSERT_DEATH(CHECK_STREQ("this", "siht"), ""); - ASSERT_DEATH(CHECK_STRCASEEQ(NULL, "siht"), ""); - ASSERT_DEATH(CHECK_STRCASEEQ("this", "siht"), ""); - ASSERT_DEATH(CHECK_STRNE(NULL, NULL), ""); - ASSERT_DEATH(CHECK_STRNE("this", "this"), ""); - ASSERT_DEATH(CHECK_STREQ((string("a")+"b").c_str(), "abc"), ""); -} - -TEST(CheckNOTNULL, Simple) { - int64 t; - void *ptr = static_cast(&t); - void *ref = CHECK_NOTNULL(ptr); - EXPECT_EQ(ptr, ref); - CHECK_NOTNULL(reinterpret_cast(ptr)); - CHECK_NOTNULL(reinterpret_cast(ptr)); - CHECK_NOTNULL(reinterpret_cast(ptr)); - CHECK_NOTNULL(reinterpret_cast(ptr)); -} - -TEST(DeathCheckNN, Simple) { - ASSERT_DEATH(CHECK_NOTNULL(static_cast(NULL)), ""); -} - -// Get list of file names that match pattern -static void GetFiles(const string& pattern, vector* files) { - files->clear(); -#if defined(HAVE_GLOB_H) - glob_t g; - const int r = glob(pattern.c_str(), 0, NULL, &g); - CHECK((r == 0) || (r == GLOB_NOMATCH)) << ": error matching " << pattern; - for (size_t i = 0; i < g.gl_pathc; i++) { - files->push_back(string(g.gl_pathv[i])); - } - globfree(&g); -#elif defined(OS_WINDOWS) - WIN32_FIND_DATAA data; - HANDLE handle = FindFirstFileA(pattern.c_str(), &data); - size_t index = pattern.rfind('\\'); - if (index == string::npos) { - LOG(FATAL) << "No directory separator."; - } - const string dirname = pattern.substr(0, index + 1); - if (handle == INVALID_HANDLE_VALUE) { - // Finding no files is OK. - return; - } - do { - files->push_back(dirname + data.cFileName); - } while (FindNextFileA(handle, &data)); - BOOL result = FindClose(handle); - LOG_SYSRESULT(result); -#else -# error There is no way to do glob. -#endif -} - -// Delete files patching pattern -static void DeleteFiles(const string& pattern) { - vector files; - GetFiles(pattern, &files); - for (size_t i = 0; i < files.size(); i++) { - CHECK(unlink(files[i].c_str()) == 0) << ": " << strerror(errno); - } -} - -static void CheckFile(const string& name, const string& expected_string) { - vector files; - GetFiles(name + "*", &files); - CHECK_EQ(files.size(), 1UL); - - FILE* file = fopen(files[0].c_str(), "r"); - CHECK(file != NULL) << ": could not open " << files[0]; - char buf[1000]; - while (fgets(buf, sizeof(buf), file) != NULL) { - if (strstr(buf, expected_string.c_str()) != NULL) { - fclose(file); - return; - } - } - fclose(file); - LOG(FATAL) << "Did not find " << expected_string << " in " << files[0]; -} - -static void TestBasename() { - fprintf(stderr, "==== Test setting log file basename\n"); - const string dest = FLAGS_test_tmpdir + "/logging_test_basename"; - DeleteFiles(dest + "*"); - - SetLogDestination(GLOG_INFO, dest.c_str()); - LOG(INFO) << "message to new base"; - FlushLogFiles(GLOG_INFO); - - CheckFile(dest, "message to new base"); - - // Release file handle for the destination file to unlock the file in Windows. - LogToStderr(); - DeleteFiles(dest + "*"); -} - -static void TestSymlink() { -#ifndef OS_WINDOWS - fprintf(stderr, "==== Test setting log file symlink\n"); - string dest = FLAGS_test_tmpdir + "/logging_test_symlink"; - string sym = FLAGS_test_tmpdir + "/symlinkbase"; - DeleteFiles(dest + "*"); - DeleteFiles(sym + "*"); - - SetLogSymlink(GLOG_INFO, "symlinkbase"); - SetLogDestination(GLOG_INFO, dest.c_str()); - LOG(INFO) << "message to new symlink"; - FlushLogFiles(GLOG_INFO); - CheckFile(sym, "message to new symlink"); - - DeleteFiles(dest + "*"); - DeleteFiles(sym + "*"); -#endif -} - -static void TestExtension() { - fprintf(stderr, "==== Test setting log file extension\n"); - string dest = FLAGS_test_tmpdir + "/logging_test_extension"; - DeleteFiles(dest + "*"); - - SetLogDestination(GLOG_INFO, dest.c_str()); - SetLogFilenameExtension("specialextension"); - LOG(INFO) << "message to new extension"; - FlushLogFiles(GLOG_INFO); - CheckFile(dest, "message to new extension"); - - // Check that file name ends with extension - vector filenames; - GetFiles(dest + "*", &filenames); - CHECK_EQ(filenames.size(), 1UL); - CHECK(strstr(filenames[0].c_str(), "specialextension") != NULL); - - // Release file handle for the destination file to unlock the file in Windows. - LogToStderr(); - DeleteFiles(dest + "*"); -} - -struct MyLogger : public base::Logger { - string data; - - virtual void Write(bool /* should_flush */, - time_t /* timestamp */, - const char* message, - int length) { - data.append(message, length); - } - - virtual void Flush() { } - - virtual uint32 LogSize() { return data.length(); } -}; - -static void TestWrapper() { - fprintf(stderr, "==== Test log wrapper\n"); - - MyLogger my_logger; - base::Logger* old_logger = base::GetLogger(GLOG_INFO); - base::SetLogger(GLOG_INFO, &my_logger); - LOG(INFO) << "Send to wrapped logger"; - FlushLogFiles(GLOG_INFO); - base::SetLogger(GLOG_INFO, old_logger); - - CHECK(strstr(my_logger.data.c_str(), "Send to wrapped logger") != NULL); -} - -static void TestErrno() { - fprintf(stderr, "==== Test errno preservation\n"); - - errno = ENOENT; - TestLogging(false); - CHECK_EQ(errno, ENOENT); -} - -static void TestOneTruncate(const char *path, int64 limit, int64 keep, - int64 dsize, int64 ksize, int64 expect) { - int fd; - CHECK_ERR(fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600)); - - const char *discardstr = "DISCARDME!", *keepstr = "KEEPME!"; - const size_t discard_size = strlen(discardstr), keep_size = strlen(keepstr); - - // Fill the file with the requested data; first discard data, then kept data - int64 written = 0; - while (written < dsize) { - int bytes = min(dsize - written, discard_size); - CHECK_ERR(write(fd, discardstr, bytes)); - written += bytes; - } - written = 0; - while (written < ksize) { - int bytes = min(ksize - written, keep_size); - CHECK_ERR(write(fd, keepstr, bytes)); - written += bytes; - } - - TruncateLogFile(path, limit, keep); - - // File should now be shorter - struct stat statbuf; - CHECK_ERR(fstat(fd, &statbuf)); - CHECK_EQ(statbuf.st_size, expect); - CHECK_ERR(lseek(fd, 0, SEEK_SET)); - - // File should contain the suffix of the original file - const size_t buf_size = statbuf.st_size + 1; - char* buf = new char[buf_size]; - memset(buf, 0, buf_size); - CHECK_ERR(read(fd, buf, buf_size)); - - const char *p = buf; - int64 checked = 0; - while (checked < expect) { - int bytes = min(expect - checked, keep_size); - CHECK(!memcmp(p, keepstr, bytes)); - checked += bytes; - } - close(fd); - delete[] buf; -} - -static void TestTruncate() { -#ifdef HAVE_UNISTD_H - fprintf(stderr, "==== Test log truncation\n"); - string path = FLAGS_test_tmpdir + "/truncatefile"; - - // Test on a small file - TestOneTruncate(path.c_str(), 10, 10, 10, 10, 10); - - // And a big file (multiple blocks to copy) - TestOneTruncate(path.c_str(), 2<<20, 4<<10, 3<<20, 4<<10, 4<<10); - - // Check edge-case limits - TestOneTruncate(path.c_str(), 10, 20, 0, 20, 20); - TestOneTruncate(path.c_str(), 10, 0, 0, 0, 0); - TestOneTruncate(path.c_str(), 10, 50, 0, 10, 10); - TestOneTruncate(path.c_str(), 50, 100, 0, 30, 30); - - // MacOSX 10.4 doesn't fail in this case. - // Windows doesn't have symlink. - // Let's just ignore this test for these cases. -#if !defined(OS_MACOSX) && !defined(OS_WINDOWS) - // Through a symlink should fail to truncate - string linkname = path + ".link"; - unlink(linkname.c_str()); - CHECK_ERR(symlink(path.c_str(), linkname.c_str())); - TestOneTruncate(linkname.c_str(), 10, 10, 0, 30, 30); -#endif - - // The /proc/self path makes sense only for linux. -#if defined(OS_LINUX) - // Through an open fd symlink should work - int fd; - CHECK_ERR(fd = open(path.c_str(), O_APPEND | O_WRONLY)); - char fdpath[64]; - snprintf(fdpath, sizeof(fdpath), "/proc/self/fd/%d", fd); - TestOneTruncate(fdpath, 10, 10, 10, 10, 10); -#endif - -#endif -} - -_START_GOOGLE_NAMESPACE_ -namespace glog_internal_namespace_ { -extern // in logging.cc -bool SafeFNMatch_(const char* pattern, size_t patt_len, - const char* str, size_t str_len); -} // namespace glog_internal_namespace_ -using glog_internal_namespace_::SafeFNMatch_; -_END_GOOGLE_NAMESPACE_ - -static bool WrapSafeFNMatch(string pattern, string str) { - pattern += "abc"; - str += "defgh"; - return SafeFNMatch_(pattern.data(), pattern.size() - 3, - str.data(), str.size() - 5); -} - -TEST(SafeFNMatch, logging) { - CHECK(WrapSafeFNMatch("foo", "foo")); - CHECK(!WrapSafeFNMatch("foo", "bar")); - CHECK(!WrapSafeFNMatch("foo", "fo")); - CHECK(!WrapSafeFNMatch("foo", "foo2")); - CHECK(WrapSafeFNMatch("bar/foo.ext", "bar/foo.ext")); - CHECK(WrapSafeFNMatch("*ba*r/fo*o.ext*", "bar/foo.ext")); - CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/baz.ext")); - CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/foo")); - CHECK(!WrapSafeFNMatch("bar/foo.ext", "bar/foo.ext.zip")); - CHECK(WrapSafeFNMatch("ba?/*.ext", "bar/foo.ext")); - CHECK(WrapSafeFNMatch("ba?/*.ext", "baZ/FOO.ext")); - CHECK(!WrapSafeFNMatch("ba?/*.ext", "barr/foo.ext")); - CHECK(!WrapSafeFNMatch("ba?/*.ext", "bar/foo.ext2")); - CHECK(WrapSafeFNMatch("ba?/*", "bar/foo.ext2")); - CHECK(WrapSafeFNMatch("ba?/*", "bar/")); - CHECK(!WrapSafeFNMatch("ba?/?", "bar/")); - CHECK(!WrapSafeFNMatch("ba?/*", "bar")); -} - -// TestWaitingLogSink will save messages here -// No lock: Accessed only by TestLogSinkWriter thread -// and after its demise by its creator. -static vector global_messages; - -// helper for TestWaitingLogSink below. -// Thread that does the logic of TestWaitingLogSink -// It's free to use LOG() itself. -class TestLogSinkWriter : public Thread { - public: - - TestLogSinkWriter() : should_exit_(false) { - SetJoinable(true); - Start(); - } - - // Just buffer it (can't use LOG() here). - void Buffer(const string& message) { - mutex_.Lock(); - RAW_LOG(INFO, "Buffering"); - messages_.push(message); - mutex_.Unlock(); - RAW_LOG(INFO, "Buffered"); - } - - // Wait for the buffer to clear (can't use LOG() here). - void Wait() { - RAW_LOG(INFO, "Waiting"); - mutex_.Lock(); - while (!NoWork()) { - mutex_.Unlock(); - SleepForMilliseconds(1); - mutex_.Lock(); - } - RAW_LOG(INFO, "Waited"); - mutex_.Unlock(); - } - - // Trigger thread exit. - void Stop() { - MutexLock l(&mutex_); - should_exit_ = true; - } - - private: - - // helpers --------------- - - // For creating a "Condition". - bool NoWork() { return messages_.empty(); } - bool HaveWork() { return !messages_.empty() || should_exit_; } - - // Thread body; CAN use LOG() here! - virtual void Run() { - while (1) { - mutex_.Lock(); - while (!HaveWork()) { - mutex_.Unlock(); - SleepForMilliseconds(1); - mutex_.Lock(); - } - if (should_exit_ && messages_.empty()) { - mutex_.Unlock(); - break; - } - // Give the main thread time to log its message, - // so that we get a reliable log capture to compare to golden file. - // Same for the other sleep below. - SleepForMilliseconds(20); - RAW_LOG(INFO, "Sink got a messages"); // only RAW_LOG under mutex_ here - string message = messages_.front(); - messages_.pop(); - // Normally this would be some more real/involved logging logic - // where LOG() usage can't be eliminated, - // e.g. pushing the message over with an RPC: - int messages_left = messages_.size(); - mutex_.Unlock(); - SleepForMilliseconds(20); - // May not use LOG while holding mutex_, because Buffer() - // acquires mutex_, and Buffer is called from LOG(), - // which has its own internal mutex: - // LOG()->LogToSinks()->TestWaitingLogSink::send()->Buffer() - LOG(INFO) << "Sink is sending out a message: " << message; - LOG(INFO) << "Have " << messages_left << " left"; - global_messages.push_back(message); - } - } - - // data --------------- - - Mutex mutex_; - bool should_exit_; - queue messages_; // messages to be logged -}; - -// A log sink that exercises WaitTillSent: -// it pushes data to a buffer and wakes up another thread to do the logging -// (that other thread can than use LOG() itself), -class TestWaitingLogSink : public LogSink { - public: - - TestWaitingLogSink() { - tid_ = pthread_self(); // for thread-specific behavior - AddLogSink(this); - } - ~TestWaitingLogSink() { - RemoveLogSink(this); - writer_.Stop(); - writer_.Join(); - } - - // (re)define LogSink interface - - virtual void send(LogSeverity severity, const char* /* full_filename */, - const char* base_filename, int line, - const struct tm* tm_time, - const char* message, size_t message_len) { - // Push it to Writer thread if we are the original logging thread. - // Note: Something like ThreadLocalLogSink is a better choice - // to do thread-specific LogSink logic for real. - if (pthread_equal(tid_, pthread_self())) { - writer_.Buffer(ToString(severity, base_filename, line, - tm_time, message, message_len)); - } - } - virtual void WaitTillSent() { - // Wait for Writer thread if we are the original logging thread. - if (pthread_equal(tid_, pthread_self())) writer_.Wait(); - } - - private: - - pthread_t tid_; - TestLogSinkWriter writer_; -}; - -// Check that LogSink::WaitTillSent can be used in the advertised way. -// We also do golden-stderr comparison. -static void TestLogSinkWaitTillSent() { - { TestWaitingLogSink sink; - // Sleeps give the sink threads time to do all their work, - // so that we get a reliable log capture to compare to the golden file. - LOG(INFO) << "Message 1"; - SleepForMilliseconds(60); - LOG(ERROR) << "Message 2"; - SleepForMilliseconds(60); - LOG(WARNING) << "Message 3"; - SleepForMilliseconds(60); - } - for (size_t i = 0; i < global_messages.size(); ++i) { - LOG(INFO) << "Sink capture: " << global_messages[i]; - } - CHECK_EQ(global_messages.size(), 3UL); -} - -TEST(Strerror, logging) { - int errcode = EINTR; - char *msg = strdup(strerror(errcode)); - const size_t buf_size = strlen(msg) + 1; - char *buf = new char[buf_size]; - CHECK_EQ(posix_strerror_r(errcode, NULL, 0), -1); - buf[0] = 'A'; - CHECK_EQ(posix_strerror_r(errcode, buf, 0), -1); - CHECK_EQ(buf[0], 'A'); - CHECK_EQ(posix_strerror_r(errcode, NULL, buf_size), -1); -#if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD) - // MacOSX or FreeBSD considers this case is an error since there is - // no enough space. - CHECK_EQ(posix_strerror_r(errcode, buf, 1), -1); -#else - CHECK_EQ(posix_strerror_r(errcode, buf, 1), 0); -#endif - CHECK_STREQ(buf, ""); - CHECK_EQ(posix_strerror_r(errcode, buf, buf_size), 0); - CHECK_STREQ(buf, msg); - delete[] buf; - CHECK_EQ(msg, StrError(errcode)); - free(msg); -} - -// Simple routines to look at the sizes of generated code for LOG(FATAL) and -// CHECK(..) via objdump -static void MyFatal() { - LOG(FATAL) << "Failed"; -} -static void MyCheck(bool a, bool b) { - CHECK_EQ(a, b); -} - -#ifdef HAVE_LIB_GMOCK - -TEST(DVLog, Basic) { - ScopedMockLog log; - -#if NDEBUG - // We are expecting that nothing is logged. - EXPECT_CALL(log, Log(_, _, _)).Times(0); -#else - EXPECT_CALL(log, Log(INFO, __FILE__, "debug log")); -#endif - - FLAGS_v = 1; - DVLOG(1) << "debug log"; -} - -TEST(DVLog, V0) { - ScopedMockLog log; - - // We are expecting that nothing is logged. - EXPECT_CALL(log, Log(_, _, _)).Times(0); - - FLAGS_v = 0; - DVLOG(1) << "debug log"; -} - -TEST(LogAtLevel, Basic) { - ScopedMockLog log; - - // The function version outputs "logging.h" as a file name. - EXPECT_CALL(log, Log(WARNING, StrNe(__FILE__), "function version")); - EXPECT_CALL(log, Log(INFO, __FILE__, "macro version")); - - int severity = WARNING; - LogAtLevel(severity, "function version"); - - severity = INFO; - // We can use the macro version as a C++ stream. - LOG_AT_LEVEL(severity) << "macro" << ' ' << "version"; -} - -TEST(TestExitOnDFatal, ToBeOrNotToBe) { - // Check the default setting... - EXPECT_TRUE(base::internal::GetExitOnDFatal()); - - // Turn off... - base::internal::SetExitOnDFatal(false); - EXPECT_FALSE(base::internal::GetExitOnDFatal()); - - // We don't die. - { - ScopedMockLog log; - //EXPECT_CALL(log, Log(_, _, _)).Times(AnyNumber()); - // LOG(DFATAL) has severity FATAL if debugging, but is - // downgraded to ERROR if not debugging. - const LogSeverity severity = -#ifdef NDEBUG - ERROR; -#else - FATAL; -#endif - EXPECT_CALL(log, Log(severity, __FILE__, "This should not be fatal")); - LOG(DFATAL) << "This should not be fatal"; - } - - // Turn back on... - base::internal::SetExitOnDFatal(true); - EXPECT_TRUE(base::internal::GetExitOnDFatal()); - -#ifdef GTEST_HAS_DEATH_TEST - // Death comes on little cats' feet. - EXPECT_DEBUG_DEATH({ - LOG(DFATAL) << "This should be fatal in debug mode"; - }, "This should be fatal in debug mode"); -#endif -} - -#ifdef HAVE_STACKTRACE - -static void BacktraceAtHelper() { - LOG(INFO) << "Not me"; - -// The vertical spacing of the next 3 lines is significant. - LOG(INFO) << "Backtrace me"; -} -static int kBacktraceAtLine = __LINE__ - 2; // The line of the LOG(INFO) above - -TEST(LogBacktraceAt, DoesNotBacktraceWhenDisabled) { - StrictMock log; - - FLAGS_log_backtrace_at = ""; - - EXPECT_CALL(log, Log(_, _, "Backtrace me")); - EXPECT_CALL(log, Log(_, _, "Not me")); - - BacktraceAtHelper(); -} - -TEST(LogBacktraceAt, DoesBacktraceAtRightLineWhenEnabled) { - StrictMock log; - - char where[100]; - snprintf(where, 100, "%s:%d", const_basename(__FILE__), kBacktraceAtLine); - FLAGS_log_backtrace_at = where; - - // The LOG at the specified line should include a stacktrace which includes - // the name of the containing function, followed by the log message. - // We use HasSubstr()s instead of ContainsRegex() for environments - // which don't have regexp. - EXPECT_CALL(log, Log(_, _, AllOf(HasSubstr("stacktrace:"), - HasSubstr("BacktraceAtHelper"), - HasSubstr("main"), - HasSubstr("Backtrace me")))); - // Other LOGs should not include a backtrace. - EXPECT_CALL(log, Log(_, _, "Not me")); - - BacktraceAtHelper(); -} - -#endif // HAVE_STACKTRACE - -#endif // HAVE_LIB_GMOCK - -struct UserDefinedClass { - bool operator==(const UserDefinedClass&) const { return true; } -}; - -inline ostream& operator<<(ostream& out, const UserDefinedClass&) { - out << "OK"; - return out; -} - -TEST(UserDefinedClass, logging) { - UserDefinedClass u; - vector buf; - LOG_STRING(INFO, &buf) << u; - CHECK_EQ(1UL, buf.size()); - CHECK(buf[0].find("OK") != string::npos); - - // We must be able to compile this. - CHECK_EQ(u, u); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_unittest.err b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_unittest.err deleted file mode 100644 index 2ecc1b070a4..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/logging_unittest.err +++ /dev/null @@ -1,307 +0,0 @@ -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=2 logtostderr=0 alsologtostderr=0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -WARNING: Logging before InitGoogleLogging() is written to STDERR -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=0 logtostderr=0 alsologtostderr=0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] foo bar 10 3.4 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 1: __SUCCESS__ [0] -EDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 3, iteration 1 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 4, iteration 1 -WDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 5, iteration 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 1 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Log if less than 3 every 2, iteration 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 2 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 3: __ENOENT__ [2] -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 3 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Log if less than 3 every 2, iteration 3 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 3, iteration 4 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 4 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 5: __EINTR__ [4] -EDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 4, iteration 5 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 5 -WDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 5, iteration 6 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 6 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 7: __ENXIO__ [6] -EDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 3, iteration 7 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 7 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 8 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Plog every 2, iteration 9: __ENOEXEC__ [8] -EDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 4, iteration 9 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 9 -EDATE TIME__ THREADID logging_unittest.cc:LINE] Log every 3, iteration 10 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Log if every 1, iteration 10 -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if this -IDATE TIME__ THREADID logging_unittest.cc:LINE] array -IDATE TIME__ THREADID logging_unittest.cc:LINE] const array -EDATE TIME__ THREADID logging_unittest.cc:LINE] foo 1000 0000001000 3e8 -EDATE TIME__ THREADID logging_unittest.cc:LINE] inner -EDATE TIME__ THREADID logging_unittest.cc:LINE] outer -no prefix -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: foo bar 10 3.400000 -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: array -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: const array -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: ptr __PTRTEST__ -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: ptr __NULLP__ -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: foo 1000 0000001000 3e8 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: foo 1000 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: foo 1000 -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: RAW_LOG ERROR: The Message was too long! -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: RAW_LOG ERROR: The Message was too long! -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 on -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 1 on -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 2 on -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=0 logtostderr=0 alsologtostderr=0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=1 stderrthreshold=0 logtostderr=0 alsologtostderr=0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=-1 stderrthreshold=0 logtostderr=0 alsologtostderr=0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=1 logtostderr=0 alsologtostderr=0 -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=2 logtostderr=0 alsologtostderr=0 -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=3 logtostderr=0 alsologtostderr=0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=3 logtostderr=1 alsologtostderr=0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=0 stderrthreshold=3 logtostderr=0 alsologtostderr=1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=1 stderrthreshold=1 logtostderr=0 alsologtostderr=0 -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Test: v=1 stderrthreshold=3 logtostderr=0 alsologtostderr=1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: vlog 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if -1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info -WDATE TIME__ THREADID logging_unittest.cc:LINE] log_if warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] log_if info every 1 expr -EDATE TIME__ THREADID logging_unittest.cc:LINE] log_if error every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] vlog_if 0 every 1 expr -IDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_STRING: reported info -WDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_STRING: reported warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_STRING: reported error -IDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected info -IDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected warning -IDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_STRING: LOG_STRING: collected error -IDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected info -WDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected error -IDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: reported info -WDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: reported warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: reported error -IDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_SINK: -IDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected info -WDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK: collected error -IDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected info -WDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_SINK_BUT_NOT_TO_LOGFILE: collected error -IDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: collected info -IDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected info -WDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: collected warning -IDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: collected error -IDATE TIME__ THREADID logging_unittest.cc:LINE] Captured by LOG_TO_STRING: LOG_TO_STRING: collected error -IDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: reported info -WDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: reported warning -EDATE TIME__ THREADID logging_unittest.cc:LINE] LOG_TO_STRING: reported error -IDATE TIME__ THREADID logging_unittest.cc:LINE] Message 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffering -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffered -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waiting -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Sink got a messages -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waited -IDATE TIME__ THREADID logging_unittest.cc:LINE] Sink is sending out a message: IDATE TIME__ THREADID logging_unittest.cc:LINE] Message 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Have 0 left -EDATE TIME__ THREADID logging_unittest.cc:LINE] Message 2 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffering -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffered -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waiting -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Sink got a messages -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waited -IDATE TIME__ THREADID logging_unittest.cc:LINE] Sink is sending out a message: EDATE TIME__ THREADID logging_unittest.cc:LINE] Message 2 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Have 0 left -WDATE TIME__ THREADID logging_unittest.cc:LINE] Message 3 -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffering -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Buffered -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waiting -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Sink got a messages -IDATE TIME__ THREADID logging_unittest.cc:LINE] RAW: Waited -IDATE TIME__ THREADID logging_unittest.cc:LINE] Sink is sending out a message: WDATE TIME__ THREADID logging_unittest.cc:LINE] Message 3 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Have 0 left -IDATE TIME__ THREADID logging_unittest.cc:LINE] Sink capture: IDATE TIME__ THREADID logging_unittest.cc:LINE] Message 1 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Sink capture: EDATE TIME__ THREADID logging_unittest.cc:LINE] Message 2 -IDATE TIME__ THREADID logging_unittest.cc:LINE] Sink capture: WDATE TIME__ THREADID logging_unittest.cc:LINE] Message 3 diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/mock-log.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/mock-log.h deleted file mode 100644 index 30a0f74efea..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/mock-log.h +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Zhanyong Wan -// -// Defines the ScopedMockLog class (using Google C++ Mocking -// Framework), which is convenient for testing code that uses LOG(). - -#ifndef GLOG_SRC_MOCK_LOG_H_ -#define GLOG_SRC_MOCK_LOG_H_ - -// For GOOGLE_NAMESPACE. This must go first so we get _XOPEN_SOURCE. -#include "utilities.h" - -#include - -#include - -#include "glog/logging.h" - -_START_GOOGLE_NAMESPACE_ -namespace glog_testing { - -// A ScopedMockLog object intercepts LOG() messages issued during its -// lifespan. Using this together with Google C++ Mocking Framework, -// it's very easy to test how a piece of code calls LOG(). The -// typical usage: -// -// TEST(FooTest, LogsCorrectly) { -// ScopedMockLog log; -// -// // We expect the WARNING "Something bad!" exactly twice. -// EXPECT_CALL(log, Log(WARNING, _, "Something bad!")) -// .Times(2); -// -// // We allow foo.cc to call LOG(INFO) any number of times. -// EXPECT_CALL(log, Log(INFO, HasSubstr("/foo.cc"), _)) -// .Times(AnyNumber()); -// -// Foo(); // Exercises the code under test. -// } -class ScopedMockLog : public GOOGLE_NAMESPACE::LogSink { - public: - // When a ScopedMockLog object is constructed, it starts to - // intercept logs. - ScopedMockLog() { AddLogSink(this); } - - // When the object is destructed, it stops intercepting logs. - virtual ~ScopedMockLog() { RemoveLogSink(this); } - - // Implements the mock method: - // - // void Log(LogSeverity severity, const string& file_path, - // const string& message); - // - // The second argument to Send() is the full path of the source file - // in which the LOG() was issued. - // - // Note, that in a multi-threaded environment, all LOG() messages from a - // single thread will be handled in sequence, but that cannot be guaranteed - // for messages from different threads. In fact, if the same or multiple - // expectations are matched on two threads concurrently, their actions will - // be executed concurrently as well and may interleave. - MOCK_METHOD3(Log, void(GOOGLE_NAMESPACE::LogSeverity severity, - const std::string& file_path, - const std::string& message)); - - private: - // Implements the send() virtual function in class LogSink. - // Whenever a LOG() statement is executed, this function will be - // invoked with information presented in the LOG(). - // - // The method argument list is long and carries much information a - // test usually doesn't care about, so we trim the list before - // forwarding the call to Log(), which is much easier to use in - // tests. - // - // We still cannot call Log() directly, as it may invoke other LOG() - // messages, either due to Invoke, or due to an error logged in - // Google C++ Mocking Framework code, which would trigger a deadlock - // since a lock is held during send(). - // - // Hence, we save the message for WaitTillSent() which will be called after - // the lock on send() is released, and we'll call Log() inside - // WaitTillSent(). Since while a single send() call may be running at a - // time, multiple WaitTillSent() calls (along with the one send() call) may - // be running simultaneously, we ensure thread-safety of the exchange between - // send() and WaitTillSent(), and that for each message, LOG(), send(), - // WaitTillSent() and Log() are executed in the same thread. - virtual void send(GOOGLE_NAMESPACE::LogSeverity severity, - const char* full_filename, - const char* /*base_filename*/, int /*line*/, - const tm* /*tm_time*/, - const char* message, size_t message_len) { - // We are only interested in the log severity, full file name, and - // log message. - message_info_.severity = severity; - message_info_.file_path = full_filename; - message_info_.message = std::string(message, message_len); - } - - // Implements the WaitTillSent() virtual function in class LogSink. - // It will be executed after send() and after the global logging lock is - // released, so calls within it (or rather within the Log() method called - // within) may also issue LOG() statements. - // - // LOG(), send(), WaitTillSent() and Log() will occur in the same thread for - // a given log message. - virtual void WaitTillSent() { - // First, and very importantly, we save a copy of the message being - // processed before calling Log(), since Log() may indirectly call send() - // and WaitTillSent() in the same thread again. - MessageInfo message_info = message_info_; - Log(message_info.severity, message_info.file_path, message_info.message); - } - - // All relevant information about a logged message that needs to be passed - // from send() to WaitTillSent(). - struct MessageInfo { - GOOGLE_NAMESPACE::LogSeverity severity; - std::string file_path; - std::string message; - }; - MessageInfo message_info_; -}; - -} // namespace glog_testing -_END_GOOGLE_NAMESPACE_ - -#endif // GLOG_SRC_MOCK_LOG_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/mock-log_test.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/mock-log_test.cc deleted file mode 100644 index 7d58a307c22..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/mock-log_test.cc +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Zhanyong Wan - -// Tests the ScopedMockLog class. - -#include "mock-log.h" - -#include - -#include -#include - -namespace { - -using GOOGLE_NAMESPACE::INFO; -using GOOGLE_NAMESPACE::WARNING; -using GOOGLE_NAMESPACE::ERROR; -using GOOGLE_NAMESPACE::glog_testing::ScopedMockLog; -using std::string; -using testing::_; -using testing::HasSubstr; -using testing::InSequence; -using testing::InvokeWithoutArgs; - -// Tests that ScopedMockLog intercepts LOG()s when it's alive. -TEST(ScopedMockLogTest, InterceptsLog) { - ScopedMockLog log; - - InSequence s; - EXPECT_CALL(log, Log(WARNING, HasSubstr("/mock-log_test.cc"), "Fishy.")); - EXPECT_CALL(log, Log(INFO, _, "Working...")) - .Times(2); - EXPECT_CALL(log, Log(ERROR, _, "Bad!!")); - - LOG(WARNING) << "Fishy."; - LOG(INFO) << "Working..."; - LOG(INFO) << "Working..."; - LOG(ERROR) << "Bad!!"; -} - -void LogBranch() { - LOG(INFO) << "Logging a branch..."; -} - -void LogTree() { - LOG(INFO) << "Logging the whole tree..."; -} - -void LogForest() { - LOG(INFO) << "Logging the entire forest."; - LOG(INFO) << "Logging the entire forest.."; - LOG(INFO) << "Logging the entire forest..."; -} - -// The purpose of the following test is to verify that intercepting logging -// continues to work properly if a LOG statement is executed within the scope -// of a mocked call. -TEST(ScopedMockLogTest, LogDuringIntercept) { - ScopedMockLog log; - InSequence s; - EXPECT_CALL(log, Log(INFO, __FILE__, "Logging a branch...")) - .WillOnce(InvokeWithoutArgs(LogTree)); - EXPECT_CALL(log, Log(INFO, __FILE__, "Logging the whole tree...")) - .WillOnce(InvokeWithoutArgs(LogForest)); - EXPECT_CALL(log, Log(INFO, __FILE__, "Logging the entire forest.")); - EXPECT_CALL(log, Log(INFO, __FILE__, "Logging the entire forest..")); - EXPECT_CALL(log, Log(INFO, __FILE__, "Logging the entire forest...")); - LogBranch(); -} - -} // namespace - -int main(int argc, char **argv) { - GOOGLE_NAMESPACE::InitGoogleLogging(argv[0]); - testing::InitGoogleMock(&argc, argv); - - return RUN_ALL_TESTS(); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/raw_logging.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/raw_logging.cc deleted file mode 100644 index 3bbfda31868..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/raw_logging.cc +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Maxim Lifantsev -// -// logging_unittest.cc covers the functionality herein - -#include "utilities.h" - -#include -#include -#include -#ifdef HAVE_UNISTD_H -# include // for close() and write() -#endif -#include // for open() -#include -#include "config.h" -#include "glog/logging.h" // To pick up flag settings etc. -#include "glog/raw_logging.h" -#include "base/commandlineflags.h" - -#ifdef HAVE_STACKTRACE -# include "stacktrace.h" -#endif - -#if defined(HAVE_SYSCALL_H) -#include // for syscall() -#elif defined(HAVE_SYS_SYSCALL_H) -#include // for syscall() -#endif -#ifdef HAVE_UNISTD_H -# include -#endif - -#if defined(HAVE_SYSCALL_H) || defined(HAVE_SYS_SYSCALL_H) -# define safe_write(fd, s, len) syscall(SYS_write, fd, s, len) -#else - // Not so safe, but what can you do? -# define safe_write(fd, s, len) write(fd, s, len) -#endif - -_START_GOOGLE_NAMESPACE_ - -// CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths -// that invoke malloc() and getenv() that might acquire some locks. -// If this becomes a problem we should reimplement a subset of vsnprintf -// that does not need locks and malloc. - -// Helper for RawLog__ below. -// *DoRawLog writes to *buf of *size and move them past the written portion. -// It returns true iff there was no overflow or error. -static bool DoRawLog(char** buf, int* size, const char* format, ...) { - va_list ap; - va_start(ap, format); - int n = vsnprintf(*buf, *size, format, ap); - va_end(ap); - if (n < 0 || n > *size) return false; - *size -= n; - *buf += n; - return true; -} - -// Helper for RawLog__ below. -inline static bool VADoRawLog(char** buf, int* size, - const char* format, va_list ap) { - int n = vsnprintf(*buf, *size, format, ap); - if (n < 0 || n > *size) return false; - *size -= n; - *buf += n; - return true; -} - -static const int kLogBufSize = 3000; -static bool crashed = false; -static CrashReason crash_reason; -static char crash_buf[kLogBufSize + 1] = { 0 }; // Will end in '\0' - -void RawLog__(LogSeverity severity, const char* file, int line, - const char* format, ...) { - if (!(FLAGS_logtostderr || severity >= FLAGS_stderrthreshold || - FLAGS_alsologtostderr || !IsGoogleLoggingInitialized())) { - return; // this stderr log message is suppressed - } - // can't call localtime_r here: it can allocate - char buffer[kLogBufSize]; - char* buf = buffer; - int size = sizeof(buffer); - - // NOTE: this format should match the specification in base/logging.h - DoRawLog(&buf, &size, "%c0000 00:00:00.000000 %5u %s:%d] RAW: ", - LogSeverityNames[severity][0], - static_cast(GetTID()), - const_basename(const_cast(file)), line); - - // Record the position and size of the buffer after the prefix - const char* msg_start = buf; - const int msg_size = size; - - va_list ap; - va_start(ap, format); - bool no_chop = VADoRawLog(&buf, &size, format, ap); - va_end(ap); - if (no_chop) { - DoRawLog(&buf, &size, "\n"); - } else { - DoRawLog(&buf, &size, "RAW_LOG ERROR: The Message was too long!\n"); - } - // We make a raw syscall to write directly to the stderr file descriptor, - // avoiding FILE buffering (to avoid invoking malloc()), and bypassing - // libc (to side-step any libc interception). - // We write just once to avoid races with other invocations of RawLog__. - safe_write(STDERR_FILENO, buffer, strlen(buffer)); - if (severity == GLOG_FATAL) { - if (!sync_val_compare_and_swap(&crashed, false, true)) { - crash_reason.filename = file; - crash_reason.line_number = line; - memcpy(crash_buf, msg_start, msg_size); // Don't include prefix - crash_reason.message = crash_buf; -#ifdef HAVE_STACKTRACE - crash_reason.depth = - GetStackTrace(crash_reason.stack, ARRAYSIZE(crash_reason.stack), 1); -#else - crash_reason.depth = 0; -#endif - SetCrashReason(&crash_reason); - } - LogMessage::Fail(); // abort() - } -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/signalhandler.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/signalhandler.cc deleted file mode 100644 index 955471899af..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/signalhandler.cc +++ /dev/null @@ -1,403 +0,0 @@ -// Copyright (c) 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Satoru Takabayashi -// -// Implementation of InstallFailureSignalHandler(). - -#include "utilities.h" -#include "stacktrace.h" -#include "symbolize.h" -#include "glog/logging.h" - -#include -#include -#ifdef HAVE_UCONTEXT_H -# include -#endif -#ifdef HAVE_SYS_UCONTEXT_H -# include -#endif -#include - -_START_GOOGLE_NAMESPACE_ - -namespace { - -// We'll install the failure signal handler for these signals. We could -// use strsignal() to get signal names, but we don't use it to avoid -// introducing yet another #ifdef complication. -// -// The list should be synced with the comment in signalhandler.h. -const struct { - int number; - const char *name; -} kFailureSignals[] = { - { SIGSEGV, "SIGSEGV" }, - { SIGILL, "SIGILL" }, - { SIGFPE, "SIGFPE" }, - { SIGABRT, "SIGABRT" }, -#if !defined(OS_WINDOWS) - { SIGBUS, "SIGBUS" }, -#endif - { SIGTERM, "SIGTERM" }, -}; - -static bool kFailureSignalHandlerInstalled = false; - -// Returns the program counter from signal context, NULL if unknown. -void* GetPC(void* ucontext_in_void) { -#if (defined(HAVE_UCONTEXT_H) || defined(HAVE_SYS_UCONTEXT_H)) && defined(PC_FROM_UCONTEXT) - if (ucontext_in_void != NULL) { - ucontext_t *context = reinterpret_cast(ucontext_in_void); - return (void*)context->PC_FROM_UCONTEXT; - } -#endif - return NULL; -} - -// The class is used for formatting error messages. We don't use printf() -// as it's not async signal safe. -class MinimalFormatter { - public: - MinimalFormatter(char *buffer, int size) - : buffer_(buffer), - cursor_(buffer), - end_(buffer + size) { - } - - // Returns the number of bytes written in the buffer. - int num_bytes_written() const { return (int) (cursor_ - buffer_); } - - // Appends string from "str" and updates the internal cursor. - void AppendString(const char* str) { - int i = 0; - while (str[i] != '\0' && cursor_ + i < end_) { - cursor_[i] = str[i]; - ++i; - } - cursor_ += i; - } - - // Formats "number" in "radix" and updates the internal cursor. - // Lowercase letters are used for 'a' - 'z'. - void AppendUint64(uint64 number, int radix) { - int i = 0; - while (cursor_ + i < end_) { - const int tmp = number % radix; - number /= radix; - cursor_[i] = (tmp < 10 ? '0' + tmp : 'a' + tmp - 10); - ++i; - if (number == 0) { - break; - } - } - // Reverse the bytes written. - std::reverse(cursor_, cursor_ + i); - cursor_ += i; - } - - // Formats "number" as hexadecimal number, and updates the internal - // cursor. Padding will be added in front if needed. - void AppendHexWithPadding(uint64 number, int width) { - char* start = cursor_; - AppendString("0x"); - AppendUint64(number, 16); - // Move to right and add padding in front if needed. - if (cursor_ < start + width) { - const int64 delta = start + width - cursor_; - std::copy(start, cursor_, start + delta); - std::fill(start, start + delta, ' '); - cursor_ = start + width; - } - } - - private: - char *buffer_; - char *cursor_; - const char * const end_; -}; - -// Writes the given data with the size to the standard error. -void WriteToStderr(const char* data, int size) { - if (write(STDERR_FILENO, data, size) < 0) { - // Ignore errors. - } -} - -// The writer function can be changed by InstallFailureWriter(). -void (*g_failure_writer)(const char* data, int size) = WriteToStderr; - -// Dumps time information. We don't dump human-readable time information -// as localtime() is not guaranteed to be async signal safe. -void DumpTimeInfo() { - time_t time_in_sec = time(NULL); - char buf[256]; // Big enough for time info. - MinimalFormatter formatter(buf, sizeof(buf)); - formatter.AppendString("*** Aborted at "); - formatter.AppendUint64(time_in_sec, 10); - formatter.AppendString(" (unix time)"); - formatter.AppendString(" try \"date -d @"); - formatter.AppendUint64(time_in_sec, 10); - formatter.AppendString("\" if you are using GNU date ***\n"); - g_failure_writer(buf, formatter.num_bytes_written()); -} - -// TODO(hamaji): Use signal instead of sigaction? -#ifdef HAVE_SIGACTION - -// Dumps information about the signal to STDERR. -void DumpSignalInfo(int signal_number, siginfo_t *siginfo) { - // Get the signal name. - const char* signal_name = NULL; - for (size_t i = 0; i < ARRAYSIZE(kFailureSignals); ++i) { - if (signal_number == kFailureSignals[i].number) { - signal_name = kFailureSignals[i].name; - } - } - - char buf[256]; // Big enough for signal info. - MinimalFormatter formatter(buf, sizeof(buf)); - - formatter.AppendString("*** "); - if (signal_name) { - formatter.AppendString(signal_name); - } else { - // Use the signal number if the name is unknown. The signal name - // should be known, but just in case. - formatter.AppendString("Signal "); - formatter.AppendUint64(signal_number, 10); - } - formatter.AppendString(" (@0x"); - formatter.AppendUint64(reinterpret_cast(siginfo->si_addr), 16); - formatter.AppendString(")"); - formatter.AppendString(" received by PID "); - formatter.AppendUint64(getpid(), 10); - formatter.AppendString(" (TID 0x"); - // We assume pthread_t is an integral number or a pointer, rather - // than a complex struct. In some environments, pthread_self() - // returns an uint64 but in some other environments pthread_self() - // returns a pointer. Hence we use C-style cast here, rather than - // reinterpret/static_cast, to support both types of environments. - formatter.AppendUint64((uintptr_t)pthread_self(), 16); - formatter.AppendString(") "); - // Only linux has the PID of the signal sender in si_pid. -#ifdef OS_LINUX - formatter.AppendString("from PID "); - formatter.AppendUint64(siginfo->si_pid, 10); - formatter.AppendString("; "); -#endif - formatter.AppendString("stack trace: ***\n"); - g_failure_writer(buf, formatter.num_bytes_written()); -} - -#endif // HAVE_SIGACTION - -// Dumps information about the stack frame to STDERR. -void DumpStackFrameInfo(const char* prefix, void* pc) { - // Get the symbol name. - const char *symbol = "(unknown)"; - char symbolized[1024]; // Big enough for a sane symbol. - // Symbolizes the previous address of pc because pc may be in the - // next function. - if (Symbolize(reinterpret_cast(pc) - 1, - symbolized, sizeof(symbolized))) { - symbol = symbolized; - } - - char buf[1024]; // Big enough for stack frame info. - MinimalFormatter formatter(buf, sizeof(buf)); - - formatter.AppendString(prefix); - formatter.AppendString("@ "); - const int width = 2 * sizeof(void*) + 2; // + 2 for "0x". - formatter.AppendHexWithPadding(reinterpret_cast(pc), width); - formatter.AppendString(" "); - formatter.AppendString(symbol); - formatter.AppendString("\n"); - g_failure_writer(buf, formatter.num_bytes_written()); -} - -// Invoke the default signal handler. -void InvokeDefaultSignalHandler(int signal_number) { -#ifdef HAVE_SIGACTION - struct sigaction sig_action; - memset(&sig_action, 0, sizeof(sig_action)); - sigemptyset(&sig_action.sa_mask); - sig_action.sa_handler = SIG_DFL; - sigaction(signal_number, &sig_action, NULL); - kill(getpid(), signal_number); -#elif defined(OS_WINDOWS) - signal(signal_number, SIG_DFL); - raise(signal_number); -#endif -} - -// This variable is used for protecting FailureSignalHandler() from -// dumping stuff while another thread is doing it. Our policy is to let -// the first thread dump stuff and let other threads wait. -// See also comments in FailureSignalHandler(). -static pthread_t* g_entered_thread_id_pointer = NULL; - -// Dumps signal and stack frame information, and invokes the default -// signal handler once our job is done. -#if defined(OS_WINDOWS) -void FailureSignalHandler(int signal_number) -#else -void FailureSignalHandler(int signal_number, - siginfo_t *signal_info, - void *ucontext) -#endif -{ - // First check if we've already entered the function. We use an atomic - // compare and swap operation for platforms that support it. For other - // platforms, we use a naive method that could lead to a subtle race. - - // We assume pthread_self() is async signal safe, though it's not - // officially guaranteed. - pthread_t my_thread_id = pthread_self(); - // NOTE: We could simply use pthread_t rather than pthread_t* for this, - // if pthread_self() is guaranteed to return non-zero value for thread - // ids, but there is no such guarantee. We need to distinguish if the - // old value (value returned from __sync_val_compare_and_swap) is - // different from the original value (in this case NULL). - pthread_t* old_thread_id_pointer = - glog_internal_namespace_::sync_val_compare_and_swap( - &g_entered_thread_id_pointer, - static_cast(NULL), - &my_thread_id); - if (old_thread_id_pointer != NULL) { - // We've already entered the signal handler. What should we do? - if (pthread_equal(my_thread_id, *g_entered_thread_id_pointer)) { - // It looks the current thread is reentering the signal handler. - // Something must be going wrong (maybe we are reentering by another - // type of signal?). Kill ourself by the default signal handler. - InvokeDefaultSignalHandler(signal_number); - } - // Another thread is dumping stuff. Let's wait until that thread - // finishes the job and kills the process. - while (true) { - sleep(1); - } - } - // This is the first time we enter the signal handler. We are going to - // do some interesting stuff from here. - // TODO(satorux): We might want to set timeout here using alarm(), but - // mixing alarm() and sleep() can be a bad idea. - - // First dump time info. - DumpTimeInfo(); - -#if !defined(OS_WINDOWS) - // Get the program counter from ucontext. - void *pc = GetPC(ucontext); - DumpStackFrameInfo("PC: ", pc); -#endif - -#ifdef HAVE_STACKTRACE - // Get the stack traces. - void *stack[32]; - // +1 to exclude this function. - const int depth = GetStackTrace(stack, ARRAYSIZE(stack), 1); -# ifdef HAVE_SIGACTION - DumpSignalInfo(signal_number, signal_info); -# endif - // Dump the stack traces. - for (int i = 0; i < depth; ++i) { - DumpStackFrameInfo(" ", stack[i]); - } -#endif - - // *** TRANSITION *** - // - // BEFORE this point, all code must be async-termination-safe! - // (See WARNING above.) - // - // AFTER this point, we do unsafe things, like using LOG()! - // The process could be terminated or hung at any time. We try to - // do more useful things first and riskier things later. - - // Flush the logs before we do anything in case 'anything' - // causes problems. - FlushLogFilesUnsafe(0); - - // Kill ourself by the default signal handler. - InvokeDefaultSignalHandler(signal_number); -} - -} // namespace - -namespace glog_internal_namespace_ { - -bool IsFailureSignalHandlerInstalled() { -#ifdef HAVE_SIGACTION - // TODO(andschwa): Return kFailureSignalHandlerInstalled? - struct sigaction sig_action; - memset(&sig_action, 0, sizeof(sig_action)); - sigemptyset(&sig_action.sa_mask); - sigaction(SIGABRT, NULL, &sig_action); - if (sig_action.sa_sigaction == &FailureSignalHandler) - return true; -#elif defined(OS_WINDOWS) - return kFailureSignalHandlerInstalled; -#endif // HAVE_SIGACTION - return false; -} - -} // namespace glog_internal_namespace_ - -void InstallFailureSignalHandler() { -#ifdef HAVE_SIGACTION - // Build the sigaction struct. - struct sigaction sig_action; - memset(&sig_action, 0, sizeof(sig_action)); - sigemptyset(&sig_action.sa_mask); - sig_action.sa_flags |= SA_SIGINFO; - sig_action.sa_sigaction = &FailureSignalHandler; - - for (size_t i = 0; i < ARRAYSIZE(kFailureSignals); ++i) { - CHECK_ERR(sigaction(kFailureSignals[i].number, &sig_action, NULL)); - } - kFailureSignalHandlerInstalled = true; -#elif defined(OS_WINDOWS) - for (size_t i = 0; i < ARRAYSIZE(kFailureSignals); ++i) { - CHECK_NE(signal(kFailureSignals[i].number, &FailureSignalHandler), - SIG_ERR); - } - kFailureSignalHandlerInstalled = true; -#endif // HAVE_SIGACTION -} - -void InstallFailureWriter(void (*writer)(const char* data, int size)) { -#if defined(HAVE_SIGACTION) || defined(OS_WINDOWS) - g_failure_writer = writer; -#endif // HAVE_SIGACTION -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/signalhandler_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/signalhandler_unittest.cc deleted file mode 100644 index 36d957b9c35..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/signalhandler_unittest.cc +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Satoru Takabayashi -// -// This is a helper binary for testing signalhandler.cc. The actual test -// is done in signalhandler_unittest.sh. - -#include "utilities.h" - -#if defined(HAVE_PTHREAD) -# include -#endif -#include -#include -#include -#include -#include "glog/logging.h" - -#ifdef HAVE_LIB_GFLAGS -#include -using namespace GFLAGS_NAMESPACE; -#endif - -using namespace GOOGLE_NAMESPACE; - -static void* DieInThread(void*) { - // We assume pthread_t is an integral number or a pointer, rather - // than a complex struct. In some environments, pthread_self() - // returns an uint64 but in some other environments pthread_self() - // returns a pointer. Hence we use C-style cast here, rather than - // reinterpret/static_cast, to support both types of environments. - fprintf(stderr, "0x%lx is dying\n", (long)pthread_self()); - // Use volatile to prevent from these to be optimized away. - volatile int a = 0; - volatile int b = 1 / a; - fprintf(stderr, "We should have died: b=%d\n", b); - return NULL; -} - -static void WriteToStdout(const char* data, int size) { - if (write(STDOUT_FILENO, data, size) < 0) { - // Ignore errors. - } -} - -int main(int argc, char **argv) { -#if defined(HAVE_STACKTRACE) && defined(HAVE_SYMBOLIZE) - InitGoogleLogging(argv[0]); -#ifdef HAVE_LIB_GFLAGS - ParseCommandLineFlags(&argc, &argv, true); -#endif - InstallFailureSignalHandler(); - const std::string command = argc > 1 ? argv[1] : "none"; - if (command == "segv") { - // We'll check if this is outputted. - LOG(INFO) << "create the log file"; - LOG(INFO) << "a message before segv"; - // We assume 0xDEAD is not writable. - int *a = (int*)0xDEAD; - *a = 0; - } else if (command == "loop") { - fprintf(stderr, "looping\n"); - while (true); - } else if (command == "die_in_thread") { -#if defined(HAVE_PTHREAD) - pthread_t thread; - pthread_create(&thread, NULL, &DieInThread, NULL); - pthread_join(thread, NULL); -#else - fprintf(stderr, "no pthread\n"); - return 1; -#endif - } else if (command == "dump_to_stdout") { - InstallFailureWriter(WriteToStdout); - abort(); - } else if (command == "installed") { - fprintf(stderr, "signal handler installed: %s\n", - IsFailureSignalHandlerInstalled() ? "true" : "false"); - } else { - // Tell the shell script - puts("OK"); - } -#endif - return 0; -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/signalhandler_unittest.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/signalhandler_unittest.sh deleted file mode 100755 index 265cd458c01..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/signalhandler_unittest.sh +++ /dev/null @@ -1,131 +0,0 @@ -#! /bin/sh -# -# Copyright (c) 2008, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# Author: Satoru Takabayashi -# -# Unit tests for signalhandler.cc. - -die () { - echo $1 - exit 1 -} - -BINDIR=".libs" -LIBGLOG="$BINDIR/libglog.so" - -BINARY="$BINDIR/signalhandler_unittest" -LOG_INFO="./signalhandler_unittest.INFO" - -# Remove temporary files. -rm -f signalhandler.out* - -if test -e "$BINARY"; then - # We need shared object. - export LD_LIBRARY_PATH=$BINDIR - export DYLD_LIBRARY_PATH=$BINDIR -else - # For windows - BINARY="./signalhandler_unittest.exe" - if ! test -e "$BINARY"; then - echo "We coundn't find demangle_unittest binary." - exit 1 - fi -fi - -if [ x`$BINARY` != 'xOK' ]; then - echo "PASS (No stacktrace support. We don't run this test.)" - exit 0 -fi - -# The PC cannot be obtained in signal handlers on PowerPC correctly. -# We just skip the test for PowerPC. -if [ x`uname -p` = x"powerpc" ]; then - echo "PASS (We don't test the signal handler on PowerPC.)" - exit 0 -fi - -# Test for a case the program kills itself by SIGSEGV. -GOOGLE_LOG_DIR=. $BINARY segv 2> signalhandler.out1 -for pattern in SIGSEGV 0xdead main "Aborted at [0-9]"; do - if ! grep --quiet "$pattern" signalhandler.out1; then - die "'$pattern' should appear in the output" - fi -done -if ! grep --quiet "a message before segv" $LOG_INFO; then - die "'a message before segv' should appear in the INFO log" -fi -rm -f $LOG_INFO - -# Test for a case the program is killed by this shell script. -# $! = the process id of the last command run in the background. -# $$ = the process id of this shell. -$BINARY loop 2> signalhandler.out2 & -# Wait until "looping" is written in the file. This indicates the program -# is ready to accept signals. -while true; do - if grep --quiet looping signalhandler.out2; then - break - fi -done -kill -TERM $! -wait $! - -from_pid='' -# Only linux has the process ID of the signal sender. -if [ x`uname` = "xLinux" ]; then - from_pid="from PID $$" -fi -for pattern in SIGTERM "by PID $!" "$from_pid" main "Aborted at [0-9]"; do - if ! grep --quiet "$pattern" signalhandler.out2; then - die "'$pattern' should appear in the output" - fi -done - -# Test for a case the program dies in a non-main thread. -$BINARY die_in_thread 2> signalhandler.out3 -EXPECTED_TID="`sed 's/ .*//; q' signalhandler.out3`" - -for pattern in SIGFPE DieInThread "TID $EXPECTED_TID" "Aborted at [0-9]"; do - if ! grep --quiet "$pattern" signalhandler.out3; then - die "'$pattern' should appear in the output" - fi -done - -# Test for a case the program installs a custom failure writer that writes -# stuff to stdout instead of stderr. -$BINARY dump_to_stdout 1> signalhandler.out4 -for pattern in SIGABRT main "Aborted at [0-9]"; do - if ! grep --quiet "$pattern" signalhandler.out4; then - die "'$pattern' should appear in the output" - fi -done - -echo PASS diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace.h deleted file mode 100644 index cb64b33a688..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace.h +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2000 - 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Routines to extract the current stack trace. These functions are -// thread-safe. - -#ifndef BASE_STACKTRACE_H_ -#define BASE_STACKTRACE_H_ - -#include "config.h" -#include "glog/logging.h" - -_START_GOOGLE_NAMESPACE_ - -// This is similar to the GetStackFrames routine, except that it returns -// the stack trace only, and not the stack frame sizes as well. -// Example: -// main() { foo(); } -// foo() { bar(); } -// bar() { -// void* result[10]; -// int depth = GetStackFrames(result, 10, 1); -// } -// -// This produces: -// result[0] foo -// result[1] main -// .... ... -// -// "result" must not be NULL. -GOOGLE_GLOG_DLL_DECL int GetStackTrace(void** result, int max_depth, int skip_count); - -_END_GOOGLE_NAMESPACE_ - -#endif // BASE_STACKTRACE_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_generic-inl.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_generic-inl.h deleted file mode 100644 index fad81d3e3f4..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_generic-inl.h +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2000 - 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Portable implementation - just use glibc -// -// Note: The glibc implementation may cause a call to malloc. -// This can cause a deadlock in HeapProfiler. -#include -#include -#include "stacktrace.h" - -_START_GOOGLE_NAMESPACE_ - -// If you change this function, also change GetStackFrames below. -int GetStackTrace(void** result, int max_depth, int skip_count) { - static const int kStackLength = 64; - void * stack[kStackLength]; - int size; - - size = backtrace(stack, kStackLength); - skip_count++; // we want to skip the current frame as well - int result_count = size - skip_count; - if (result_count < 0) - result_count = 0; - if (result_count > max_depth) - result_count = max_depth; - for (int i = 0; i < result_count; i++) - result[i] = stack[i + skip_count]; - - return result_count; -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_libunwind-inl.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_libunwind-inl.h deleted file mode 100644 index 0dc14c6506e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_libunwind-inl.h +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2005 - 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Arun Sharma -// -// Produce stack trace using libunwind - -#include "utilities.h" - -extern "C" { -#define UNW_LOCAL_ONLY -#include -} -#include "glog/raw_logging.h" -#include "stacktrace.h" - -_START_GOOGLE_NAMESPACE_ - -// Sometimes, we can try to get a stack trace from within a stack -// trace, because libunwind can call mmap (maybe indirectly via an -// internal mmap based memory allocator), and that mmap gets trapped -// and causes a stack-trace request. If were to try to honor that -// recursive request, we'd end up with infinite recursion or deadlock. -// Luckily, it's safe to ignore those subsequent traces. In such -// cases, we return 0 to indicate the situation. -static bool g_now_entering = false; - -// If you change this function, also change GetStackFrames below. -int GetStackTrace(void** result, int max_depth, int skip_count) { - void *ip; - int n = 0; - unw_cursor_t cursor; - unw_context_t uc; - - if (sync_val_compare_and_swap(&g_now_entering, false, true)) { - return 0; - } - - unw_getcontext(&uc); - RAW_CHECK(unw_init_local(&cursor, &uc) >= 0, "unw_init_local failed"); - skip_count++; // Do not include the "GetStackTrace" frame - - while (n < max_depth) { - int ret = unw_get_reg(&cursor, UNW_REG_IP, (unw_word_t *) &ip); - if (ret < 0) - break; - if (skip_count > 0) { - skip_count--; - } else { - result[n++] = ip; - } - ret = unw_step(&cursor); - if (ret <= 0) - break; - } - - g_now_entering = false; - return n; -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_powerpc-inl.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_powerpc-inl.h deleted file mode 100644 index 03b91089aad..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_powerpc-inl.h +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Craig Silverstein -// -// Produce stack trace. I'm guessing (hoping!) the code is much like -// for x86. For apple machines, at least, it seems to be; see -// http://developer.apple.com/documentation/mac/runtimehtml/RTArch-59.html -// http://www.linux-foundation.org/spec/ELF/ppc64/PPC-elf64abi-1.9.html#STACK -// Linux has similar code: http://patchwork.ozlabs.org/linuxppc/patch?id=8882 - -#include -#include // for uintptr_t -#include "stacktrace.h" - -_START_GOOGLE_NAMESPACE_ - -// Given a pointer to a stack frame, locate and return the calling -// stackframe, or return NULL if no stackframe can be found. Perform sanity -// checks (the strictness of which is controlled by the boolean parameter -// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. -template -static void **NextStackFrame(void **old_sp) { - void **new_sp = (void **) *old_sp; - - // Check that the transition from frame pointer old_sp to frame - // pointer new_sp isn't clearly bogus - if (STRICT_UNWINDING) { - // With the stack growing downwards, older stack frame must be - // at a greater address that the current one. - if (new_sp <= old_sp) return NULL; - // Assume stack frames larger than 100,000 bytes are bogus. - if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return NULL; - } else { - // In the non-strict mode, allow discontiguous stack frames. - // (alternate-signal-stacks for example). - if (new_sp == old_sp) return NULL; - // And allow frames upto about 1MB. - if ((new_sp > old_sp) - && ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) return NULL; - } - if ((uintptr_t)new_sp & (sizeof(void *) - 1)) return NULL; - return new_sp; -} - -// This ensures that GetStackTrace stes up the Link Register properly. -void StacktracePowerPCDummyFunction() __attribute__((noinline)); -void StacktracePowerPCDummyFunction() { __asm__ volatile(""); } - -// If you change this function, also change GetStackFrames below. -int GetStackTrace(void** result, int max_depth, int skip_count) { - void **sp; - // Apple OS X uses an old version of gnu as -- both Darwin 7.9.0 (Panther) - // and Darwin 8.8.1 (Tiger) use as 1.38. This means we have to use a - // different asm syntax. I don't know quite the best way to discriminate - // systems using the old as from the new one; I've gone with __APPLE__. -#ifdef __APPLE__ - __asm__ volatile ("mr %0,r1" : "=r" (sp)); -#else - __asm__ volatile ("mr %0,1" : "=r" (sp)); -#endif - - // On PowerPC, the "Link Register" or "Link Record" (LR), is a stack - // entry that holds the return address of the subroutine call (what - // instruction we run after our function finishes). This is the - // same as the stack-pointer of our parent routine, which is what we - // want here. While the compiler will always(?) set up LR for - // subroutine calls, it may not for leaf functions (such as this one). - // This routine forces the compiler (at least gcc) to push it anyway. - StacktracePowerPCDummyFunction(); - - // The LR save area is used by the callee, so the top entry is bogus. - skip_count++; - - int n = 0; - while (sp && n < max_depth) { - if (skip_count > 0) { - skip_count--; - } else { - // PowerPC has 3 main ABIs, which say where in the stack the - // Link Register is. For DARWIN and AIX (used by apple and - // linux ppc64), it's in sp[2]. For SYSV (used by linux ppc), - // it's in sp[1]. -#if defined(_CALL_AIX) || defined(_CALL_DARWIN) - result[n++] = *(sp+2); -#elif defined(_CALL_SYSV) - result[n++] = *(sp+1); -#elif defined(__APPLE__) || ((defined(__linux) || defined(__linux__)) && defined(__PPC64__)) - // This check is in case the compiler doesn't define _CALL_AIX/etc. - result[n++] = *(sp+2); -#elif defined(__linux) - // This check is in case the compiler doesn't define _CALL_SYSV. - result[n++] = *(sp+1); -#else -#error Need to specify the PPC ABI for your archiecture. -#endif - } - // Use strict unwinding rules. - sp = NextStackFrame(sp); - } - return n; -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_unittest.cc deleted file mode 100644 index 77d34291b38..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_unittest.cc +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright (c) 2004, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#include "utilities.h" - -#include -#include -#include "config.h" -#include "base/commandlineflags.h" -#include "glog/logging.h" -#include "stacktrace.h" - -#ifdef HAVE_EXECINFO_H -# include -#endif - -using namespace GOOGLE_NAMESPACE; - -#ifdef HAVE_STACKTRACE - -// Obtain a backtrace, verify that the expected callers are present in the -// backtrace, and maybe print the backtrace to stdout. - -// The sequence of functions whose return addresses we expect to see in the -// backtrace. -const int BACKTRACE_STEPS = 6; - -struct AddressRange { - const void *start, *end; -}; - -// Expected function [start,end] range. -AddressRange expected_range[BACKTRACE_STEPS]; - -#if __GNUC__ -// Using GCC extension: address of a label can be taken with '&&label'. -// Start should be a label somewhere before recursive call, end somewhere -// after it. -#define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ - do { \ - (prange)->start = &&start_label; \ - (prange)->end = &&end_label; \ - CHECK_LT((prange)->start, (prange)->end); \ - } while (0) -// This macro expands into "unmovable" code (opaque to GCC), and that -// prevents GCC from moving a_label up or down in the code. -// Without it, there is no code following the 'end' label, and GCC -// (4.3.1, 4.4.0) thinks it safe to assign &&end an address that is before -// the recursive call. -#define DECLARE_ADDRESS_LABEL(a_label) \ - a_label: do { __asm__ __volatile__(""); } while (0) -// Gcc 4.4.0 may split function into multiple chunks, and the chunk -// performing recursive call may end up later in the code then the return -// instruction (this actually happens with FDO). -// Adjust function range from __builtin_return_address. -#define ADJUST_ADDRESS_RANGE_FROM_RA(prange) \ - do { \ - void *ra = __builtin_return_address(0); \ - CHECK_LT((prange)->start, ra); \ - if (ra > (prange)->end) { \ - printf("Adjusting range from %p..%p to %p..%p\n", \ - (prange)->start, (prange)->end, \ - (prange)->start, ra); \ - (prange)->end = ra; \ - } \ - } while (0) -#else -// Assume the Check* functions below are not longer than 256 bytes. -#define INIT_ADDRESS_RANGE(fn, start_label, end_label, prange) \ - do { \ - (prange)->start = reinterpret_cast(&fn); \ - (prange)->end = reinterpret_cast(&fn) + 256; \ - } while (0) -#define DECLARE_ADDRESS_LABEL(a_label) do { } while (0) -#define ADJUST_ADDRESS_RANGE_FROM_RA(prange) do { } while (0) -#endif // __GNUC__ - -//-----------------------------------------------------------------------// - -static void CheckRetAddrIsInFunction(void *ret_addr, const AddressRange &range) -{ - CHECK_GE(ret_addr, range.start); - CHECK_LE(ret_addr, range.end); -} - -//-----------------------------------------------------------------------// - -void ATTRIBUTE_NOINLINE CheckStackTrace(int); -static void ATTRIBUTE_NOINLINE CheckStackTraceLeaf(void) { - const int STACK_LEN = 10; - void *stack[STACK_LEN]; - int size; - - ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[1]); - INIT_ADDRESS_RANGE(CheckStackTraceLeaf, start, end, &expected_range[0]); - DECLARE_ADDRESS_LABEL(start); - size = GetStackTrace(stack, STACK_LEN, 0); - printf("Obtained %d stack frames.\n", size); - CHECK_GE(size, 1); - CHECK_LE(size, STACK_LEN); - - if (1) { -#ifdef HAVE_EXECINFO_H - char **strings = backtrace_symbols(stack, size); - printf("Obtained %d stack frames.\n", size); - for (int i = 0; i < size; i++) - printf("%s %p\n", strings[i], stack[i]); - printf("CheckStackTrace() addr: %p\n", &CheckStackTrace); - free(strings); -#endif - } - for (int i = 0; i < BACKTRACE_STEPS; i++) { - printf("Backtrace %d: expected: %p..%p actual: %p ... ", - i, expected_range[i].start, expected_range[i].end, stack[i]); - fflush(stdout); - CheckRetAddrIsInFunction(stack[i], expected_range[i]); - printf("OK\n"); - } - DECLARE_ADDRESS_LABEL(end); -} - -//-----------------------------------------------------------------------// - -/* Dummy functions to make the backtrace more interesting. */ -static void ATTRIBUTE_NOINLINE CheckStackTrace4(int i) { - ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[2]); - INIT_ADDRESS_RANGE(CheckStackTrace4, start, end, &expected_range[1]); - DECLARE_ADDRESS_LABEL(start); - for (int j = i; j >= 0; j--) - CheckStackTraceLeaf(); - DECLARE_ADDRESS_LABEL(end); -} -static void ATTRIBUTE_NOINLINE CheckStackTrace3(int i) { - ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[3]); - INIT_ADDRESS_RANGE(CheckStackTrace3, start, end, &expected_range[2]); - DECLARE_ADDRESS_LABEL(start); - for (int j = i; j >= 0; j--) - CheckStackTrace4(j); - DECLARE_ADDRESS_LABEL(end); -} -static void ATTRIBUTE_NOINLINE CheckStackTrace2(int i) { - ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[4]); - INIT_ADDRESS_RANGE(CheckStackTrace2, start, end, &expected_range[3]); - DECLARE_ADDRESS_LABEL(start); - for (int j = i; j >= 0; j--) - CheckStackTrace3(j); - DECLARE_ADDRESS_LABEL(end); -} -static void ATTRIBUTE_NOINLINE CheckStackTrace1(int i) { - ADJUST_ADDRESS_RANGE_FROM_RA(&expected_range[5]); - INIT_ADDRESS_RANGE(CheckStackTrace1, start, end, &expected_range[4]); - DECLARE_ADDRESS_LABEL(start); - for (int j = i; j >= 0; j--) - CheckStackTrace2(j); - DECLARE_ADDRESS_LABEL(end); -} -#ifndef __GNUC__ -// On non-GNU environment, we use the address of `CheckStackTrace` to -// guess the address range of this function. This guess is wrong for -// non-static function on Windows. This is probably because -// `&CheckStackTrace` returns the address of a trampoline like PLT, -// not the actual address of `CheckStackTrace`. -// See https://github.com/google/glog/issues/421 for the detail. -static -#endif -void ATTRIBUTE_NOINLINE CheckStackTrace(int i) { - INIT_ADDRESS_RANGE(CheckStackTrace, start, end, &expected_range[5]); - DECLARE_ADDRESS_LABEL(start); - for (int j = i; j >= 0; j--) - CheckStackTrace1(j); - DECLARE_ADDRESS_LABEL(end); -} - -//-----------------------------------------------------------------------// - -int main(int, char ** argv) { - FLAGS_logtostderr = true; - InitGoogleLogging(argv[0]); - - CheckStackTrace(0); - - printf("PASS\n"); - return 0; -} - -#else -int main() { - printf("PASS (no stacktrace support)\n"); - return 0; -} -#endif // HAVE_STACKTRACE diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_windows-inl.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_windows-inl.h deleted file mode 100644 index 726318879d8..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_windows-inl.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2000 - 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Andrew Schwartzmeyer -// -// Windows implementation - just use CaptureStackBackTrace - -#include "config.h" -#include "port.h" -#include "stacktrace.h" -#include - -_START_GOOGLE_NAMESPACE_ - -int GetStackTrace(void** result, int max_depth, int skip_count) { - if (max_depth > 64) { - max_depth = 64; - } - skip_count++; // we want to skip the current frame as well - // This API is thread-safe (moreover it walks only the current thread). - return CaptureStackBackTrace(skip_count, max_depth, result, NULL); -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_x86-inl.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_x86-inl.h deleted file mode 100644 index 3b8d5a8282d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_x86-inl.h +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) 2000 - 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Produce stack trace - -#include // for uintptr_t - -#include "utilities.h" // for OS_* macros - -#if !defined(OS_WINDOWS) -#include -#include -#endif - -#include // for NULL -#include "stacktrace.h" - -_START_GOOGLE_NAMESPACE_ - -// Given a pointer to a stack frame, locate and return the calling -// stackframe, or return NULL if no stackframe can be found. Perform sanity -// checks (the strictness of which is controlled by the boolean parameter -// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned. -template -static void **NextStackFrame(void **old_sp) { - void **new_sp = (void **) *old_sp; - - // Check that the transition from frame pointer old_sp to frame - // pointer new_sp isn't clearly bogus - if (STRICT_UNWINDING) { - // With the stack growing downwards, older stack frame must be - // at a greater address that the current one. - if (new_sp <= old_sp) return NULL; - // Assume stack frames larger than 100,000 bytes are bogus. - if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return NULL; - } else { - // In the non-strict mode, allow discontiguous stack frames. - // (alternate-signal-stacks for example). - if (new_sp == old_sp) return NULL; - // And allow frames upto about 1MB. - if ((new_sp > old_sp) - && ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) return NULL; - } - if ((uintptr_t)new_sp & (sizeof(void *) - 1)) return NULL; -#ifdef __i386__ - // On 64-bit machines, the stack pointer can be very close to - // 0xffffffff, so we explicitly check for a pointer into the - // last two pages in the address space - if ((uintptr_t)new_sp >= 0xffffe000) return NULL; -#endif -#if !defined(OS_WINDOWS) - if (!STRICT_UNWINDING) { - // Lax sanity checks cause a crash in 32-bit tcmalloc/crash_reason_test - // on AMD-based machines with VDSO-enabled kernels. - // Make an extra sanity check to insure new_sp is readable. - // Note: NextStackFrame() is only called while the program - // is already on its last leg, so it's ok to be slow here. - static int page_size = getpagesize(); - void *new_sp_aligned = (void *)((uintptr_t)new_sp & ~(page_size - 1)); - if (msync(new_sp_aligned, page_size, MS_ASYNC) == -1) - return NULL; - } -#endif - return new_sp; -} - -// If you change this function, also change GetStackFrames below. -int GetStackTrace(void** result, int max_depth, int skip_count) { - void **sp; - -#ifdef __GNUC__ -#if __GNUC__ * 100 + __GNUC_MINOR__ >= 402 -#define USE_BUILTIN_FRAME_ADDRESS -#endif -#endif - -#ifdef USE_BUILTIN_FRAME_ADDRESS - sp = reinterpret_cast(__builtin_frame_address(0)); -#elif defined(__i386__) - // Stack frame format: - // sp[0] pointer to previous frame - // sp[1] caller address - // sp[2] first argument - // ... - sp = (void **)&result - 2; -#elif defined(__x86_64__) - // __builtin_frame_address(0) can return the wrong address on gcc-4.1.0-k8 - unsigned long rbp; - // Move the value of the register %rbp into the local variable rbp. - // We need 'volatile' to prevent this instruction from getting moved - // around during optimization to before function prologue is done. - // An alternative way to achieve this - // would be (before this __asm__ instruction) to call Noop() defined as - // static void Noop() __attribute__ ((noinline)); // prevent inlining - // static void Noop() { asm(""); } // prevent optimizing-away - __asm__ volatile ("mov %%rbp, %0" : "=r" (rbp)); - // Arguments are passed in registers on x86-64, so we can't just - // offset from &result - sp = (void **) rbp; -#endif - - int n = 0; - while (sp && n < max_depth) { - if (*(sp+1) == (void *)0) { - // In 64-bit code, we often see a frame that - // points to itself and has a return address of 0. - break; - } - if (skip_count > 0) { - skip_count--; - } else { - result[n++] = *(sp+1); - } - // Use strict unwinding rules. - sp = NextStackFrame(sp); - } - return n; -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_x86_64-inl.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_x86_64-inl.h deleted file mode 100644 index f7d1dca85bc..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stacktrace_x86_64-inl.h +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2005 - 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Arun Sharma -// -// Produce stack trace using libgcc - -extern "C" { -#include // for NULL -#include // ABI defined unwinder -} -#include "stacktrace.h" - -_START_GOOGLE_NAMESPACE_ - -typedef struct { - void **result; - int max_depth; - int skip_count; - int count; -} trace_arg_t; - - -// Workaround for the malloc() in _Unwind_Backtrace() issue. -static _Unwind_Reason_Code nop_backtrace(struct _Unwind_Context *uc, void *opq) { - return _URC_NO_REASON; -} - - -// This code is not considered ready to run until -// static initializers run so that we are guaranteed -// that any malloc-related initialization is done. -static bool ready_to_run = false; -class StackTraceInit { - public: - StackTraceInit() { - // Extra call to force initialization - _Unwind_Backtrace(nop_backtrace, NULL); - ready_to_run = true; - } -}; - -static StackTraceInit module_initializer; // Force initialization - -static _Unwind_Reason_Code GetOneFrame(struct _Unwind_Context *uc, void *opq) { - trace_arg_t *targ = (trace_arg_t *) opq; - - if (targ->skip_count > 0) { - targ->skip_count--; - } else { - targ->result[targ->count++] = (void *) _Unwind_GetIP(uc); - } - - if (targ->count == targ->max_depth) - return _URC_END_OF_STACK; - - return _URC_NO_REASON; -} - -// If you change this function, also change GetStackFrames below. -int GetStackTrace(void** result, int max_depth, int skip_count) { - if (!ready_to_run) - return 0; - - trace_arg_t targ; - - skip_count += 1; // Do not include the "GetStackTrace" frame - - targ.result = result; - targ.max_depth = max_depth; - targ.skip_count = skip_count; - targ.count = 0; - - _Unwind_Backtrace(GetOneFrame, &targ); - - return targ.count; -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stl_logging_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stl_logging_unittest.cc deleted file mode 100644 index 269094c07bf..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/stl_logging_unittest.cc +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) 2003, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#include "config.h" - -#ifdef HAVE_USING_OPERATOR - -#include -#include -#include -#include -#include -#include - -#ifdef __GNUC__ -// C++0x isn't enabled by default in GCC and libc++ does not have -// non-standard ext/* and tr1/unordered_*. -# if defined(_LIBCPP_VERSION) -# ifndef GLOG_STL_LOGGING_FOR_UNORDERED -# define GLOG_STL_LOGGING_FOR_UNORDERED -# endif -# else -# ifndef GLOG_STL_LOGGING_FOR_EXT_HASH -# define GLOG_STL_LOGGING_FOR_EXT_HASH -# endif -# ifndef GLOG_STL_LOGGING_FOR_EXT_SLIST -# define GLOG_STL_LOGGING_FOR_EXT_SLIST -# endif -# ifndef GLOG_STL_LOGGING_FOR_TR1_UNORDERED -# define GLOG_STL_LOGGING_FOR_TR1_UNORDERED -# endif -# endif -#endif - -#include "glog/logging.h" -#include "glog/stl_logging.h" -#include "googletest.h" - -using namespace std; -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH -using namespace __gnu_cxx; -#endif - -struct user_hash { - size_t operator()(int x) const { return x; } -}; - -static void TestSTLLogging() { - { - // Test a sequence. - vector v; - v.push_back(10); - v.push_back(20); - v.push_back(30); - ostringstream ss; - ss << v; - EXPECT_EQ(ss.str(), "10 20 30"); - vector copied_v(v); - CHECK_EQ(v, copied_v); // This must compile. - } - - { - // Test a sorted pair associative container. - map< int, string > m; - m[20] = "twenty"; - m[10] = "ten"; - m[30] = "thirty"; - ostringstream ss; - ss << m; - EXPECT_EQ(ss.str(), "(10, ten) (20, twenty) (30, thirty)"); - map< int, string > copied_m(m); - CHECK_EQ(m, copied_m); // This must compile. - } - -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH - { - // Test a hashed simple associative container. - hash_set hs; - hs.insert(10); - hs.insert(20); - hs.insert(30); - ostringstream ss; - ss << hs; - EXPECT_EQ(ss.str(), "10 20 30"); - hash_set copied_hs(hs); - CHECK_EQ(hs, copied_hs); // This must compile. - } -#endif - -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH - { - // Test a hashed pair associative container. - hash_map hm; - hm[10] = "ten"; - hm[20] = "twenty"; - hm[30] = "thirty"; - ostringstream ss; - ss << hm; - EXPECT_EQ(ss.str(), "(10, ten) (20, twenty) (30, thirty)"); - hash_map copied_hm(hm); - CHECK_EQ(hm, copied_hm); // this must compile - } -#endif - - { - // Test a long sequence. - vector v; - string expected; - for (int i = 0; i < 100; i++) { - v.push_back(i); - if (i > 0) expected += ' '; - char buf[256]; - sprintf(buf, "%d", i); - expected += buf; - } - v.push_back(100); - expected += " ..."; - ostringstream ss; - ss << v; - CHECK_EQ(ss.str(), expected.c_str()); - } - - { - // Test a sorted pair associative container. - // Use a non-default comparison functor. - map< int, string, greater > m; - m[20] = "twenty"; - m[10] = "ten"; - m[30] = "thirty"; - ostringstream ss; - ss << m; - EXPECT_EQ(ss.str(), "(30, thirty) (20, twenty) (10, ten)"); - map< int, string, greater > copied_m(m); - CHECK_EQ(m, copied_m); // This must compile. - } - -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH - { - // Test a hashed simple associative container. - // Use a user defined hash function. - hash_set hs; - hs.insert(10); - hs.insert(20); - hs.insert(30); - ostringstream ss; - ss << hs; - EXPECT_EQ(ss.str(), "10 20 30"); - hash_set copied_hs(hs); - CHECK_EQ(hs, copied_hs); // This must compile. - } -#endif -} - -int main(int, char**) { - TestSTLLogging(); - std::cout << "PASS\n"; - return 0; -} - -#else - -#include - -int main(int, char**) { - std::cout << "We don't support stl_logging for this compiler.\n" - << "(we need compiler support of 'using ::operator<<' " - << "for this feature.)\n"; - return 0; -} - -#endif // HAVE_USING_OPERATOR diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/symbolize.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/symbolize.cc deleted file mode 100644 index 1ffc6079a2a..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/symbolize.cc +++ /dev/null @@ -1,952 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Satoru Takabayashi -// Stack-footprint reduction work done by Raksit Ashok -// -// Implementation note: -// -// We don't use heaps but only use stacks. We want to reduce the -// stack consumption so that the symbolizer can run on small stacks. -// -// Here are some numbers collected with GCC 4.1.0 on x86: -// - sizeof(Elf32_Sym) = 16 -// - sizeof(Elf32_Shdr) = 40 -// - sizeof(Elf64_Sym) = 24 -// - sizeof(Elf64_Shdr) = 64 -// -// This implementation is intended to be async-signal-safe but uses -// some functions which are not guaranteed to be so, such as memchr() -// and memmove(). We assume they are async-signal-safe. -// -// Additional header can be specified by the GLOG_BUILD_CONFIG_INCLUDE -// macro to add platform specific defines (e.g. OS_OPENBSD). - -#ifdef GLOG_BUILD_CONFIG_INCLUDE -#include GLOG_BUILD_CONFIG_INCLUDE -#endif // GLOG_BUILD_CONFIG_INCLUDE - -#include "utilities.h" - -#if defined(HAVE_SYMBOLIZE) - -#include - -#include -#include - -#include "symbolize.h" -#include "demangle.h" - -_START_GOOGLE_NAMESPACE_ - -// We don't use assert() since it's not guaranteed to be -// async-signal-safe. Instead we define a minimal assertion -// macro. So far, we don't need pretty printing for __FILE__, etc. - -// A wrapper for abort() to make it callable in ? :. -static int AssertFail() { - abort(); - return 0; // Should not reach. -} - -#define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail()) - -static SymbolizeCallback g_symbolize_callback = NULL; -void InstallSymbolizeCallback(SymbolizeCallback callback) { - g_symbolize_callback = callback; -} - -static SymbolizeOpenObjectFileCallback g_symbolize_open_object_file_callback = - NULL; -void InstallSymbolizeOpenObjectFileCallback( - SymbolizeOpenObjectFileCallback callback) { - g_symbolize_open_object_file_callback = callback; -} - -// This function wraps the Demangle function to provide an interface -// where the input symbol is demangled in-place. -// To keep stack consumption low, we would like this function to not -// get inlined. -static ATTRIBUTE_NOINLINE void DemangleInplace(char *out, int out_size) { - char demangled[256]; // Big enough for sane demangled symbols. - if (Demangle(out, demangled, sizeof(demangled))) { - // Demangling succeeded. Copy to out if the space allows. - size_t len = strlen(demangled); - if (len + 1 <= (size_t)out_size) { // +1 for '\0'. - SAFE_ASSERT(len < sizeof(demangled)); - memmove(out, demangled, len + 1); - } - } -} - -_END_GOOGLE_NAMESPACE_ - -#if defined(__ELF__) - -#include -#if defined(OS_OPENBSD) -#include -#else -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "symbolize.h" -#include "config.h" -#include "glog/raw_logging.h" - -// Re-runs fn until it doesn't cause EINTR. -#define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR) - -_START_GOOGLE_NAMESPACE_ - -// Read up to "count" bytes from "offset" in the file pointed by file -// descriptor "fd" into the buffer starting at "buf" while handling short reads -// and EINTR. On success, return the number of bytes read. Otherwise, return -// -1. -static ssize_t ReadFromOffset(const int fd, void *buf, const size_t count, - const off_t offset) { - SAFE_ASSERT(fd >= 0); - SAFE_ASSERT(count <= std::numeric_limits::max()); - char *buf0 = reinterpret_cast(buf); - ssize_t num_bytes = 0; - while (num_bytes < count) { - ssize_t len; - NO_INTR(len = pread(fd, buf0 + num_bytes, count - num_bytes, - offset + num_bytes)); - if (len < 0) { // There was an error other than EINTR. - return -1; - } - if (len == 0) { // Reached EOF. - break; - } - num_bytes += len; - } - SAFE_ASSERT(num_bytes <= count); - return num_bytes; -} - -// Try reading exactly "count" bytes from "offset" bytes in a file -// pointed by "fd" into the buffer starting at "buf" while handling -// short reads and EINTR. On success, return true. Otherwise, return -// false. -static bool ReadFromOffsetExact(const int fd, void *buf, - const size_t count, const off_t offset) { - ssize_t len = ReadFromOffset(fd, buf, count, offset); - return len == count; -} - -// Returns elf_header.e_type if the file pointed by fd is an ELF binary. -static int FileGetElfType(const int fd) { - ElfW(Ehdr) elf_header; - if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { - return -1; - } - if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) { - return -1; - } - return elf_header.e_type; -} - -// Read the section headers in the given ELF binary, and if a section -// of the specified type is found, set the output to this section header -// and return true. Otherwise, return false. -// To keep stack consumption low, we would like this function to not get -// inlined. -static ATTRIBUTE_NOINLINE bool -GetSectionHeaderByType(const int fd, ElfW(Half) sh_num, const off_t sh_offset, - ElfW(Word) type, ElfW(Shdr) *out) { - // Read at most 16 section headers at a time to save read calls. - ElfW(Shdr) buf[16]; - for (int i = 0; i < sh_num;) { - const ssize_t num_bytes_left = (sh_num - i) * sizeof(buf[0]); - const ssize_t num_bytes_to_read = - (sizeof(buf) > num_bytes_left) ? num_bytes_left : sizeof(buf); - const ssize_t len = ReadFromOffset(fd, buf, num_bytes_to_read, - sh_offset + i * sizeof(buf[0])); - if (len == -1) { - return false; - } - SAFE_ASSERT(len % sizeof(buf[0]) == 0); - const ssize_t num_headers_in_buf = len / sizeof(buf[0]); - SAFE_ASSERT(num_headers_in_buf <= sizeof(buf) / sizeof(buf[0])); - for (int j = 0; j < num_headers_in_buf; ++j) { - if (buf[j].sh_type == type) { - *out = buf[j]; - return true; - } - } - i += num_headers_in_buf; - } - return false; -} - -// There is no particular reason to limit section name to 63 characters, -// but there has (as yet) been no need for anything longer either. -const int kMaxSectionNameLen = 64; - -// name_len should include terminating '\0'. -bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, - ElfW(Shdr) *out) { - ElfW(Ehdr) elf_header; - if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { - return false; - } - - ElfW(Shdr) shstrtab; - off_t shstrtab_offset = (elf_header.e_shoff + - elf_header.e_shentsize * elf_header.e_shstrndx); - if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) { - return false; - } - - for (int i = 0; i < elf_header.e_shnum; ++i) { - off_t section_header_offset = (elf_header.e_shoff + - elf_header.e_shentsize * i); - if (!ReadFromOffsetExact(fd, out, sizeof(*out), section_header_offset)) { - return false; - } - char header_name[kMaxSectionNameLen]; - if (sizeof(header_name) < name_len) { - RAW_LOG(WARNING, "Section name '%s' is too long (%" PRIuS "); " - "section will not be found (even if present).", name, name_len); - // No point in even trying. - return false; - } - off_t name_offset = shstrtab.sh_offset + out->sh_name; - ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset); - if (n_read == -1) { - return false; - } else if (n_read != name_len) { - // Short read -- name could be at end of file. - continue; - } - if (memcmp(header_name, name, name_len) == 0) { - return true; - } - } - return false; -} - -// Read a symbol table and look for the symbol containing the -// pc. Iterate over symbols in a symbol table and look for the symbol -// containing "pc". On success, return true and write the symbol name -// to out. Otherwise, return false. -// To keep stack consumption low, we would like this function to not get -// inlined. -static ATTRIBUTE_NOINLINE bool -FindSymbol(uint64_t pc, const int fd, char *out, int out_size, - uint64_t symbol_offset, const ElfW(Shdr) *strtab, - const ElfW(Shdr) *symtab) { - if (symtab == NULL) { - return false; - } - const int num_symbols = symtab->sh_size / symtab->sh_entsize; - for (int i = 0; i < num_symbols;) { - off_t offset = symtab->sh_offset + i * symtab->sh_entsize; - - // If we are reading Elf64_Sym's, we want to limit this array to - // 32 elements (to keep stack consumption low), otherwise we can - // have a 64 element Elf32_Sym array. -#if __WORDSIZE == 64 -#define NUM_SYMBOLS 32 -#else -#define NUM_SYMBOLS 64 -#endif - - // Read at most NUM_SYMBOLS symbols at once to save read() calls. - ElfW(Sym) buf[NUM_SYMBOLS]; - int num_symbols_to_read = std::min(NUM_SYMBOLS, num_symbols - i); - const ssize_t len = - ReadFromOffset(fd, &buf, sizeof(buf[0]) * num_symbols_to_read, offset); - SAFE_ASSERT(len % sizeof(buf[0]) == 0); - const ssize_t num_symbols_in_buf = len / sizeof(buf[0]); - SAFE_ASSERT(num_symbols_in_buf <= num_symbols_to_read); - for (int j = 0; j < num_symbols_in_buf; ++j) { - const ElfW(Sym)& symbol = buf[j]; - uint64_t start_address = symbol.st_value; - start_address += symbol_offset; - uint64_t end_address = start_address + symbol.st_size; - if (symbol.st_value != 0 && // Skip null value symbols. - symbol.st_shndx != 0 && // Skip undefined symbols. - start_address <= pc && pc < end_address) { - ssize_t len1 = ReadFromOffset(fd, out, out_size, - strtab->sh_offset + symbol.st_name); - if (len1 <= 0 || memchr(out, '\0', out_size) == NULL) { - return false; - } - return true; // Obtained the symbol name. - } - } - i += num_symbols_in_buf; - } - return false; -} - -// Get the symbol name of "pc" from the file pointed by "fd". Process -// both regular and dynamic symbol tables if necessary. On success, -// write the symbol name to "out" and return true. Otherwise, return -// false. -static bool GetSymbolFromObjectFile(const int fd, - uint64_t pc, - char* out, - int out_size, - uint64_t base_address) { - // Read the ELF header. - ElfW(Ehdr) elf_header; - if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) { - return false; - } - - ElfW(Shdr) symtab, strtab; - - // Consult a regular symbol table first. - if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff, - SHT_SYMTAB, &symtab)) { - if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff + - symtab.sh_link * sizeof(symtab))) { - return false; - } - if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { - return true; // Found the symbol in a regular symbol table. - } - } - - // If the symbol is not found, then consult a dynamic symbol table. - if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff, - SHT_DYNSYM, &symtab)) { - if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff + - symtab.sh_link * sizeof(symtab))) { - return false; - } - if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) { - return true; // Found the symbol in a dynamic symbol table. - } - } - - return false; -} - -namespace { -// Thin wrapper around a file descriptor so that the file descriptor -// gets closed for sure. -struct FileDescriptor { - const int fd_; - explicit FileDescriptor(int fd) : fd_(fd) {} - ~FileDescriptor() { - if (fd_ >= 0) { - NO_INTR(close(fd_)); - } - } - int get() { return fd_; } - - private: - explicit FileDescriptor(const FileDescriptor&); - void operator=(const FileDescriptor&); -}; - -// Helper class for reading lines from file. -// -// Note: we don't use ProcMapsIterator since the object is big (it has -// a 5k array member) and uses async-unsafe functions such as sscanf() -// and snprintf(). -class LineReader { - public: - explicit LineReader(int fd, char *buf, int buf_len, off_t offset) - : fd_(fd), - buf_(buf), - buf_len_(buf_len), - offset_(offset), - bol_(buf), - eol_(buf), - eod_(buf) {} - - // Read '\n'-terminated line from file. On success, modify "bol" - // and "eol", then return true. Otherwise, return false. - // - // Note: if the last line doesn't end with '\n', the line will be - // dropped. It's an intentional behavior to make the code simple. - bool ReadLine(const char **bol, const char **eol) { - if (BufferIsEmpty()) { // First time. - const ssize_t num_bytes = ReadFromOffset(fd_, buf_, buf_len_, offset_); - if (num_bytes <= 0) { // EOF or error. - return false; - } - offset_ += num_bytes; - eod_ = buf_ + num_bytes; - bol_ = buf_; - } else { - bol_ = eol_ + 1; // Advance to the next line in the buffer. - SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_". - if (!HasCompleteLine()) { - const int incomplete_line_length = eod_ - bol_; - // Move the trailing incomplete line to the beginning. - memmove(buf_, bol_, incomplete_line_length); - // Read text from file and append it. - char * const append_pos = buf_ + incomplete_line_length; - const int capacity_left = buf_len_ - incomplete_line_length; - const ssize_t num_bytes = - ReadFromOffset(fd_, append_pos, capacity_left, offset_); - if (num_bytes <= 0) { // EOF or error. - return false; - } - offset_ += num_bytes; - eod_ = append_pos + num_bytes; - bol_ = buf_; - } - } - eol_ = FindLineFeed(); - if (eol_ == NULL) { // '\n' not found. Malformed line. - return false; - } - *eol_ = '\0'; // Replace '\n' with '\0'. - - *bol = bol_; - *eol = eol_; - return true; - } - - // Beginning of line. - const char *bol() { - return bol_; - } - - // End of line. - const char *eol() { - return eol_; - } - - private: - explicit LineReader(const LineReader&); - void operator=(const LineReader&); - - char *FindLineFeed() { - return reinterpret_cast(memchr(bol_, '\n', eod_ - bol_)); - } - - bool BufferIsEmpty() { - return buf_ == eod_; - } - - bool HasCompleteLine() { - return !BufferIsEmpty() && FindLineFeed() != NULL; - } - - const int fd_; - char * const buf_; - const int buf_len_; - off_t offset_; - char *bol_; - char *eol_; - const char *eod_; // End of data in "buf_". -}; -} // namespace - -// Place the hex number read from "start" into "*hex". The pointer to -// the first non-hex character or "end" is returned. -static char *GetHex(const char *start, const char *end, uint64_t *hex) { - *hex = 0; - const char *p; - for (p = start; p < end; ++p) { - int ch = *p; - if ((ch >= '0' && ch <= '9') || - (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) { - *hex = (*hex << 4) | (ch < 'A' ? ch - '0' : (ch & 0xF) + 9); - } else { // Encountered the first non-hex character. - break; - } - } - SAFE_ASSERT(p <= end); - return const_cast(p); -} - -// Searches for the object file (from /proc/self/maps) that contains -// the specified pc. If found, sets |start_address| to the start address -// of where this object file is mapped in memory, sets the module base -// address into |base_address|, copies the object file name into -// |out_file_name|, and attempts to open the object file. If the object -// file is opened successfully, returns the file descriptor. Otherwise, -// returns -1. |out_file_name_size| is the size of the file name buffer -// (including the null-terminator). -static ATTRIBUTE_NOINLINE int -OpenObjectFileContainingPcAndGetStartAddress(uint64_t pc, - uint64_t &start_address, - uint64_t &base_address, - char *out_file_name, - int out_file_name_size) { - int object_fd; - - int maps_fd; - NO_INTR(maps_fd = open("/proc/self/maps", O_RDONLY)); - FileDescriptor wrapped_maps_fd(maps_fd); - if (wrapped_maps_fd.get() < 0) { - return -1; - } - - int mem_fd; - NO_INTR(mem_fd = open("/proc/self/mem", O_RDONLY)); - FileDescriptor wrapped_mem_fd(mem_fd); - if (wrapped_mem_fd.get() < 0) { - return -1; - } - - // Iterate over maps and look for the map containing the pc. Then - // look into the symbol tables inside. - char buf[1024]; // Big enough for line of sane /proc/self/maps - int num_maps = 0; - LineReader reader(wrapped_maps_fd.get(), buf, sizeof(buf), 0); - while (true) { - num_maps++; - const char *cursor; - const char *eol; - if (!reader.ReadLine(&cursor, &eol)) { // EOF or malformed line. - return -1; - } - - // Start parsing line in /proc/self/maps. Here is an example: - // - // 08048000-0804c000 r-xp 00000000 08:01 2142121 /bin/cat - // - // We want start address (08048000), end address (0804c000), flags - // (r-xp) and file name (/bin/cat). - - // Read start address. - cursor = GetHex(cursor, eol, &start_address); - if (cursor == eol || *cursor != '-') { - return -1; // Malformed line. - } - ++cursor; // Skip '-'. - - // Read end address. - uint64_t end_address; - cursor = GetHex(cursor, eol, &end_address); - if (cursor == eol || *cursor != ' ') { - return -1; // Malformed line. - } - ++cursor; // Skip ' '. - - // Read flags. Skip flags until we encounter a space or eol. - const char * const flags_start = cursor; - while (cursor < eol && *cursor != ' ') { - ++cursor; - } - // We expect at least four letters for flags (ex. "r-xp"). - if (cursor == eol || cursor < flags_start + 4) { - return -1; // Malformed line. - } - - // Determine the base address by reading ELF headers in process memory. - ElfW(Ehdr) ehdr; - // Skip non-readable maps. - if (flags_start[0] == 'r' && - ReadFromOffsetExact(mem_fd, &ehdr, sizeof(ElfW(Ehdr)), start_address) && - memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) { - switch (ehdr.e_type) { - case ET_EXEC: - base_address = 0; - break; - case ET_DYN: - // Find the segment containing file offset 0. This will correspond - // to the ELF header that we just read. Normally this will have - // virtual address 0, but this is not guaranteed. We must subtract - // the virtual address from the address where the ELF header was - // mapped to get the base address. - // - // If we fail to find a segment for file offset 0, use the address - // of the ELF header as the base address. - base_address = start_address; - for (unsigned i = 0; i != ehdr.e_phnum; ++i) { - ElfW(Phdr) phdr; - if (ReadFromOffsetExact( - mem_fd, &phdr, sizeof(phdr), - start_address + ehdr.e_phoff + i * sizeof(phdr)) && - phdr.p_type == PT_LOAD && phdr.p_offset == 0) { - base_address = start_address - phdr.p_vaddr; - break; - } - } - break; - default: - // ET_REL or ET_CORE. These aren't directly executable, so they don't - // affect the base address. - break; - } - } - - // Check start and end addresses. - if (!(start_address <= pc && pc < end_address)) { - continue; // We skip this map. PC isn't in this map. - } - - // Check flags. We are only interested in "r*x" maps. - if (flags_start[0] != 'r' || flags_start[2] != 'x') { - continue; // We skip this map. - } - ++cursor; // Skip ' '. - - // Read file offset. - uint64_t file_offset; - cursor = GetHex(cursor, eol, &file_offset); - if (cursor == eol || *cursor != ' ') { - return -1; // Malformed line. - } - ++cursor; // Skip ' '. - - // Skip to file name. "cursor" now points to dev. We need to - // skip at least two spaces for dev and inode. - int num_spaces = 0; - while (cursor < eol) { - if (*cursor == ' ') { - ++num_spaces; - } else if (num_spaces >= 2) { - // The first non-space character after skipping two spaces - // is the beginning of the file name. - break; - } - ++cursor; - } - if (cursor == eol) { - return -1; // Malformed line. - } - - // Finally, "cursor" now points to file name of our interest. - NO_INTR(object_fd = open(cursor, O_RDONLY)); - if (object_fd < 0) { - // Failed to open object file. Copy the object file name to - // |out_file_name|. - strncpy(out_file_name, cursor, out_file_name_size); - // Making sure |out_file_name| is always null-terminated. - out_file_name[out_file_name_size - 1] = '\0'; - return -1; - } - return object_fd; - } -} - -// POSIX doesn't define any async-signal safe function for converting -// an integer to ASCII. We'll have to define our own version. -// itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the -// conversion was successful or NULL otherwise. It never writes more than "sz" -// bytes. Output will be truncated as needed, and a NUL character is always -// appended. -// NOTE: code from sandbox/linux/seccomp-bpf/demo.cc. -static char *itoa_r(intptr_t i, char *buf, size_t sz, int base, size_t padding) { - // Make sure we can write at least one NUL byte. - size_t n = 1; - if (n > sz) - return NULL; - - if (base < 2 || base > 16) { - buf[0] = '\000'; - return NULL; - } - - char *start = buf; - - uintptr_t j = i; - - // Handle negative numbers (only for base 10). - if (i < 0 && base == 10) { - // This does "j = -i" while avoiding integer overflow. - j = static_cast(-(i + 1)) + 1; - - // Make sure we can write the '-' character. - if (++n > sz) { - buf[0] = '\000'; - return NULL; - } - *start++ = '-'; - } - - // Loop until we have converted the entire number. Output at least one - // character (i.e. '0'). - char *ptr = start; - do { - // Make sure there is still enough space left in our output buffer. - if (++n > sz) { - buf[0] = '\000'; - return NULL; - } - - // Output the next digit. - *ptr++ = "0123456789abcdef"[j % base]; - j /= base; - - if (padding > 0) - padding--; - } while (j > 0 || padding > 0); - - // Terminate the output with a NUL character. - *ptr = '\000'; - - // Conversion to ASCII actually resulted in the digits being in reverse - // order. We can't easily generate them in forward order, as we can't tell - // the number of characters needed until we are done converting. - // So, now, we reverse the string (except for the possible "-" sign). - while (--ptr > start) { - char ch = *ptr; - *ptr = *start; - *start++ = ch; - } - return buf; -} - -// Safely appends string |source| to string |dest|. Never writes past the -// buffer size |dest_size| and guarantees that |dest| is null-terminated. -static void SafeAppendString(const char* source, char* dest, int dest_size) { - int dest_string_length = strlen(dest); - SAFE_ASSERT(dest_string_length < dest_size); - dest += dest_string_length; - dest_size -= dest_string_length; - strncpy(dest, source, dest_size); - // Making sure |dest| is always null-terminated. - dest[dest_size - 1] = '\0'; -} - -// Converts a 64-bit value into a hex string, and safely appends it to |dest|. -// Never writes past the buffer size |dest_size| and guarantees that |dest| is -// null-terminated. -static void SafeAppendHexNumber(uint64_t value, char* dest, int dest_size) { - // 64-bit numbers in hex can have up to 16 digits. - char buf[17] = {'\0'}; - SafeAppendString(itoa_r(value, buf, sizeof(buf), 16, 0), dest, dest_size); -} - -// The implementation of our symbolization routine. If it -// successfully finds the symbol containing "pc" and obtains the -// symbol name, returns true and write the symbol name to "out". -// Otherwise, returns false. If Callback function is installed via -// InstallSymbolizeCallback(), the function is also called in this function, -// and "out" is used as its output. -// To keep stack consumption low, we would like this function to not -// get inlined. -static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, - int out_size) { - uint64_t pc0 = reinterpret_cast(pc); - uint64_t start_address = 0; - uint64_t base_address = 0; - int object_fd = -1; - - if (out_size < 1) { - return false; - } - out[0] = '\0'; - SafeAppendString("(", out, out_size); - - if (g_symbolize_open_object_file_callback) { - object_fd = g_symbolize_open_object_file_callback(pc0, start_address, - base_address, out + 1, - out_size - 1); - } else { - object_fd = OpenObjectFileContainingPcAndGetStartAddress(pc0, start_address, - base_address, - out + 1, - out_size - 1); - } - -#if defined(PRINT_UNSYMBOLIZED_STACK_TRACES) - { - FileDescriptor wrapped_object_fd(object_fd); -#else - // Check whether a file name was returned. - if (object_fd < 0) { -#endif - if (out[1]) { - // The object file containing PC was determined successfully however the - // object file was not opened successfully. This is still considered - // success because the object file name and offset are known and tools - // like asan_symbolize.py can be used for the symbolization. - out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated. - SafeAppendString("+0x", out, out_size); - SafeAppendHexNumber(pc0 - base_address, out, out_size); - SafeAppendString(")", out, out_size); - return true; - } - // Failed to determine the object file containing PC. Bail out. - return false; - } - FileDescriptor wrapped_object_fd(object_fd); - int elf_type = FileGetElfType(wrapped_object_fd.get()); - if (elf_type == -1) { - return false; - } - if (g_symbolize_callback) { - // Run the call back if it's installed. - // Note: relocation (and much of the rest of this code) will be - // wrong for prelinked shared libraries and PIE executables. - uint64_t relocation = (elf_type == ET_DYN) ? start_address : 0; - int num_bytes_written = g_symbolize_callback(wrapped_object_fd.get(), - pc, out, out_size, - relocation); - if (num_bytes_written > 0) { - out += num_bytes_written; - out_size -= num_bytes_written; - } - } - if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0, - out, out_size, base_address)) { - return false; - } - - // Symbolization succeeded. Now we try to demangle the symbol. - DemangleInplace(out, out_size); - return true; -} - -_END_GOOGLE_NAMESPACE_ - -#elif defined(OS_MACOSX) && defined(HAVE_DLADDR) - -#include -#include - -_START_GOOGLE_NAMESPACE_ - -static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, - int out_size) { - Dl_info info; - if (dladdr(pc, &info)) { - if ((int)strlen(info.dli_sname) < out_size) { - strcpy(out, info.dli_sname); - // Symbolization succeeded. Now we try to demangle the symbol. - DemangleInplace(out, out_size); - return true; - } - } - return false; -} - -_END_GOOGLE_NAMESPACE_ - -#elif defined(OS_WINDOWS) || defined(OS_CYGWIN) - -#include -#include - -#ifdef _MSC_VER -#pragma comment(lib, "dbghelp") -#endif - -_START_GOOGLE_NAMESPACE_ - -class SymInitializer { -public: - HANDLE process; - bool ready; - SymInitializer() : process(NULL), ready(false) { - // Initialize the symbol handler. - // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680344(v=vs.85).aspx - process = GetCurrentProcess(); - // Defer symbol loading. - // We do not request undecorated symbols with SYMOPT_UNDNAME - // because the mangling library calls UnDecorateSymbolName. - SymSetOptions(SYMOPT_DEFERRED_LOADS); - if (SymInitialize(process, NULL, true)) { - ready = true; - } - } - ~SymInitializer() { - SymCleanup(process); - // We do not need to close `HANDLE process` because it's a "pseudo handle." - } -private: - SymInitializer(const SymInitializer&); - SymInitializer& operator=(const SymInitializer&); -}; - -static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out, - int out_size) { - const static SymInitializer symInitializer; - if (!symInitializer.ready) { - return false; - } - // Resolve symbol information from address. - // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680578(v=vs.85).aspx - char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; - SYMBOL_INFO *symbol = reinterpret_cast(buf); - symbol->SizeOfStruct = sizeof(SYMBOL_INFO); - symbol->MaxNameLen = MAX_SYM_NAME; - // We use the ANSI version to ensure the string type is always `char *`. - // This could break if a symbol has Unicode in it. - BOOL ret = SymFromAddr(symInitializer.process, - reinterpret_cast(pc), 0, symbol); - if (ret == 1 && static_cast(symbol->NameLen) < out_size) { - // `NameLen` does not include the null terminating character. - strncpy(out, symbol->Name, static_cast(symbol->NameLen) + 1); - out[static_cast(symbol->NameLen)] = '\0'; - // Symbolization succeeded. Now we try to demangle the symbol. - DemangleInplace(out, out_size); - return true; - } - return false; -} - -_END_GOOGLE_NAMESPACE_ - -#else -# error BUG: HAVE_SYMBOLIZE was wrongly set -#endif - -_START_GOOGLE_NAMESPACE_ - -bool Symbolize(void *pc, char *out, int out_size) { - SAFE_ASSERT(out_size >= 0); - return SymbolizeAndDemangle(pc, out, out_size); -} - -_END_GOOGLE_NAMESPACE_ - -#else /* HAVE_SYMBOLIZE */ - -#include - -#include "config.h" - -_START_GOOGLE_NAMESPACE_ - -// TODO: Support other environments. -bool Symbolize(void *pc, char *out, int out_size) { - assert(0); - return false; -} - -_END_GOOGLE_NAMESPACE_ - -#endif diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/symbolize.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/symbolize.h deleted file mode 100644 index c6f9ec4360e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/symbolize.h +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Satoru Takabayashi -// -// This library provides Symbolize() function that symbolizes program -// counters to their corresponding symbol names on linux platforms. -// This library has a minimal implementation of an ELF symbol table -// reader (i.e. it doesn't depend on libelf, etc.). -// -// The algorithm used in Symbolize() is as follows. -// -// 1. Go through a list of maps in /proc/self/maps and find the map -// containing the program counter. -// -// 2. Open the mapped file and find a regular symbol table inside. -// Iterate over symbols in the symbol table and look for the symbol -// containing the program counter. If such a symbol is found, -// obtain the symbol name, and demangle the symbol if possible. -// If the symbol isn't found in the regular symbol table (binary is -// stripped), try the same thing with a dynamic symbol table. -// -// Note that Symbolize() is originally implemented to be used in -// FailureSignalHandler() in base/google.cc. Hence it doesn't use -// malloc() and other unsafe operations. It should be both -// thread-safe and async-signal-safe. - -#ifndef BASE_SYMBOLIZE_H_ -#define BASE_SYMBOLIZE_H_ - -#include "utilities.h" -#include "config.h" -#include "glog/logging.h" - -#ifdef HAVE_SYMBOLIZE - -#if defined(__ELF__) // defined by gcc -#if defined(__OpenBSD__) -#include -#else -#include -#endif - -#if !defined(ANDROID) -#include // For ElfW() macro. -#endif - -// For systems where SIZEOF_VOID_P is not defined, determine it -// based on __LP64__ (defined by gcc on 64-bit systems) -#if !defined(SIZEOF_VOID_P) -# if defined(__LP64__) -# define SIZEOF_VOID_P 8 -# else -# define SIZEOF_VOID_P 4 -# endif -#endif - -// If there is no ElfW macro, let's define it by ourself. -#ifndef ElfW -# if SIZEOF_VOID_P == 4 -# define ElfW(type) Elf32_##type -# elif SIZEOF_VOID_P == 8 -# define ElfW(type) Elf64_##type -# else -# error "Unknown sizeof(void *)" -# endif -#endif - -_START_GOOGLE_NAMESPACE_ - -// Gets the section header for the given name, if it exists. Returns true on -// success. Otherwise, returns false. -bool GetSectionHeaderByName(int fd, const char *name, size_t name_len, - ElfW(Shdr) *out); - -_END_GOOGLE_NAMESPACE_ - -#endif /* __ELF__ */ - -_START_GOOGLE_NAMESPACE_ - -// Restrictions on the callbacks that follow: -// - The callbacks must not use heaps but only use stacks. -// - The callbacks must be async-signal-safe. - -// Installs a callback function, which will be called right before a symbol name -// is printed. The callback is intended to be used for showing a file name and a -// line number preceding a symbol name. -// "fd" is a file descriptor of the object file containing the program -// counter "pc". The callback function should write output to "out" -// and return the size of the output written. On error, the callback -// function should return -1. -typedef int (*SymbolizeCallback)(int fd, - void* pc, - char* out, - size_t out_size, - uint64_t relocation); -void InstallSymbolizeCallback(SymbolizeCallback callback); - -// Installs a callback function, which will be called instead of -// OpenObjectFileContainingPcAndGetStartAddress. The callback is expected -// to searches for the object file (from /proc/self/maps) that contains -// the specified pc. If found, sets |start_address| to the start address -// of where this object file is mapped in memory, sets the module base -// address into |base_address|, copies the object file name into -// |out_file_name|, and attempts to open the object file. If the object -// file is opened successfully, returns the file descriptor. Otherwise, -// returns -1. |out_file_name_size| is the size of the file name buffer -// (including the null-terminator). -typedef int (*SymbolizeOpenObjectFileCallback)(uint64_t pc, - uint64_t& start_address, - uint64_t& base_address, - char* out_file_name, - int out_file_name_size); -void InstallSymbolizeOpenObjectFileCallback( - SymbolizeOpenObjectFileCallback callback); - -_END_GOOGLE_NAMESPACE_ - -#endif - -_START_GOOGLE_NAMESPACE_ - -// Symbolizes a program counter. On success, returns true and write the -// symbol name to "out". The symbol name is demangled if possible -// (supports symbols generated by GCC 3.x or newer). Otherwise, -// returns false. -GOOGLE_GLOG_DLL_DECL bool Symbolize(void *pc, char *out, int out_size); - -_END_GOOGLE_NAMESPACE_ - -#endif // BASE_SYMBOLIZE_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/symbolize_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/symbolize_unittest.cc deleted file mode 100644 index 9a17e7b2aa2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/symbolize_unittest.cc +++ /dev/null @@ -1,425 +0,0 @@ -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Satoru Takabayashi -// -// Unit tests for functions in symbolize.cc. - -#include "utilities.h" - -#include -#include - -#include "glog/logging.h" -#include "symbolize.h" -#include "googletest.h" -#include "config.h" - -#ifdef HAVE_LIB_GFLAGS -#include -using namespace GFLAGS_NAMESPACE; -#endif - -using namespace std; -using namespace GOOGLE_NAMESPACE; - -#if defined(HAVE_STACKTRACE) - -#define always_inline - -// A wrapper function for Symbolize() to make the unit test simple. -static const char *TrySymbolize(void *pc) { - static char symbol[4096]; - if (Symbolize(pc, symbol, sizeof(symbol))) { - return symbol; - } else { - return NULL; - } -} - -# if defined(__ELF__) - -// This unit tests make sense only with GCC. -// Uses lots of GCC specific features. -#if defined(__GNUC__) && !defined(__OPENCC__) -# if __GNUC__ >= 4 -# define TEST_WITH_MODERN_GCC -# if __i386__ // always_inline isn't supported for x86_64 with GCC 4.1.0. -# undef always_inline -# define always_inline __attribute__((always_inline)) -# define HAVE_ALWAYS_INLINE -# endif // __i386__ -# else -# endif // __GNUC__ >= 4 -# if defined(__i386__) || defined(__x86_64__) -# define TEST_X86_32_AND_64 1 -# endif // defined(__i386__) || defined(__x86_64__) -#endif - -// Make them C linkage to avoid mangled names. -extern "C" { -void nonstatic_func(); -void nonstatic_func() { - volatile int a = 0; - ++a; -} - -static void static_func() { - volatile int a = 0; - ++a; -} -} - -TEST(Symbolize, Symbolize) { - // We do C-style cast since GCC 2.95.3 doesn't allow - // reinterpret_cast(&func). - - // Compilers should give us pointers to them. - EXPECT_STREQ("nonstatic_func", TrySymbolize((void *)(&nonstatic_func))); - - // The name of an internal linkage symbol is not specified; allow either a - // mangled or an unmangled name here. - const char *static_func_symbol = TrySymbolize((void *)(&static_func)); - CHECK(NULL != static_func_symbol); - EXPECT_TRUE(strcmp("static_func", static_func_symbol) == 0 || - strcmp("static_func()", static_func_symbol) == 0); - - EXPECT_TRUE(NULL == TrySymbolize(NULL)); -} - -struct Foo { - static void func(int x); -}; - -void ATTRIBUTE_NOINLINE Foo::func(int x) { - volatile int a = x; - ++a; -} - -// With a modern GCC, Symbolize() should return demangled symbol -// names. Function parameters should be omitted. -#ifdef TEST_WITH_MODERN_GCC -TEST(Symbolize, SymbolizeWithDemangling) { - Foo::func(100); - EXPECT_STREQ("Foo::func()", TrySymbolize((void *)(&Foo::func))); -} -#endif - -// Tests that verify that Symbolize footprint is within some limit. - -// To measure the stack footprint of the Symbolize function, we create -// a signal handler (for SIGUSR1 say) that calls the Symbolize function -// on an alternate stack. This alternate stack is initialized to some -// known pattern (0x55, 0x55, 0x55, ...). We then self-send this signal, -// and after the signal handler returns, look at the alternate stack -// buffer to see what portion has been touched. -// -// This trick gives us the the stack footprint of the signal handler. -// But the signal handler, even before the call to Symbolize, consumes -// some stack already. We however only want the stack usage of the -// Symbolize function. To measure this accurately, we install two signal -// handlers: one that does nothing and just returns, and another that -// calls Symbolize. The difference between the stack consumption of these -// two signals handlers should give us the Symbolize stack foorprint. - -static void *g_pc_to_symbolize; -static char g_symbolize_buffer[4096]; -static char *g_symbolize_result; - -static void EmptySignalHandler(int signo) {} - -static void SymbolizeSignalHandler(int signo) { - if (Symbolize(g_pc_to_symbolize, g_symbolize_buffer, - sizeof(g_symbolize_buffer))) { - g_symbolize_result = g_symbolize_buffer; - } else { - g_symbolize_result = NULL; - } -} - -const int kAlternateStackSize = 8096; -const char kAlternateStackFillValue = 0x55; - -// These helper functions look at the alternate stack buffer, and figure -// out what portion of this buffer has been touched - this is the stack -// consumption of the signal handler running on this alternate stack. -static ATTRIBUTE_NOINLINE bool StackGrowsDown(int *x) { - int y; - return &y < x; -} -static int GetStackConsumption(const char* alt_stack) { - int x; - if (StackGrowsDown(&x)) { - for (int i = 0; i < kAlternateStackSize; i++) { - if (alt_stack[i] != kAlternateStackFillValue) { - return (kAlternateStackSize - i); - } - } - } else { - for (int i = (kAlternateStackSize - 1); i >= 0; i--) { - if (alt_stack[i] != kAlternateStackFillValue) { - return i; - } - } - } - return -1; -} - -#ifdef HAVE_SIGALTSTACK - -// Call Symbolize and figure out the stack footprint of this call. -static const char *SymbolizeStackConsumption(void *pc, int *stack_consumed) { - - g_pc_to_symbolize = pc; - - // The alt-signal-stack cannot be heap allocated because there is a - // bug in glibc-2.2 where some signal handler setup code looks at the - // current stack pointer to figure out what thread is currently running. - // Therefore, the alternate stack must be allocated from the main stack - // itself. - char altstack[kAlternateStackSize]; - memset(altstack, kAlternateStackFillValue, kAlternateStackSize); - - // Set up the alt-signal-stack (and save the older one). - stack_t sigstk; - memset(&sigstk, 0, sizeof(stack_t)); - stack_t old_sigstk; - sigstk.ss_sp = altstack; - sigstk.ss_size = kAlternateStackSize; - sigstk.ss_flags = 0; - CHECK_ERR(sigaltstack(&sigstk, &old_sigstk)); - - // Set up SIGUSR1 and SIGUSR2 signal handlers (and save the older ones). - struct sigaction sa; - memset(&sa, 0, sizeof(struct sigaction)); - struct sigaction old_sa1, old_sa2; - sigemptyset(&sa.sa_mask); - sa.sa_flags = SA_ONSTACK; - - // SIGUSR1 maps to EmptySignalHandler. - sa.sa_handler = EmptySignalHandler; - CHECK_ERR(sigaction(SIGUSR1, &sa, &old_sa1)); - - // SIGUSR2 maps to SymbolizeSignalHanlder. - sa.sa_handler = SymbolizeSignalHandler; - CHECK_ERR(sigaction(SIGUSR2, &sa, &old_sa2)); - - // Send SIGUSR1 signal and measure the stack consumption of the empty - // signal handler. - CHECK_ERR(kill(getpid(), SIGUSR1)); - int stack_consumption1 = GetStackConsumption(altstack); - - // Send SIGUSR2 signal and measure the stack consumption of the symbolize - // signal handler. - CHECK_ERR(kill(getpid(), SIGUSR2)); - int stack_consumption2 = GetStackConsumption(altstack); - - // The difference between the two stack consumption values is the - // stack footprint of the Symbolize function. - if (stack_consumption1 != -1 && stack_consumption2 != -1) { - *stack_consumed = stack_consumption2 - stack_consumption1; - } else { - *stack_consumed = -1; - } - - // Log the stack consumption values. - LOG(INFO) << "Stack consumption of empty signal handler: " - << stack_consumption1; - LOG(INFO) << "Stack consumption of symbolize signal handler: " - << stack_consumption2; - LOG(INFO) << "Stack consumption of Symbolize: " << *stack_consumed; - - // Now restore the old alt-signal-stack and signal handlers. - CHECK_ERR(sigaltstack(&old_sigstk, NULL)); - CHECK_ERR(sigaction(SIGUSR1, &old_sa1, NULL)); - CHECK_ERR(sigaction(SIGUSR2, &old_sa2, NULL)); - - return g_symbolize_result; -} - -#ifdef __ppc64__ -// Symbolize stack consumption should be within 4kB. -const int kStackConsumptionUpperLimit = 4096; -#else -// Symbolize stack consumption should be within 2kB. -const int kStackConsumptionUpperLimit = 2048; -#endif - -TEST(Symbolize, SymbolizeStackConsumption) { - int stack_consumed; - const char* symbol; - - symbol = SymbolizeStackConsumption((void *)(&nonstatic_func), - &stack_consumed); - EXPECT_STREQ("nonstatic_func", symbol); - EXPECT_GT(stack_consumed, 0); - EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); - - // The name of an internal linkage symbol is not specified; allow either a - // mangled or an unmangled name here. - symbol = SymbolizeStackConsumption((void *)(&static_func), - &stack_consumed); - CHECK(NULL != symbol); - EXPECT_TRUE(strcmp("static_func", symbol) == 0 || - strcmp("static_func()", symbol) == 0); - EXPECT_GT(stack_consumed, 0); - EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); -} - -#ifdef TEST_WITH_MODERN_GCC -TEST(Symbolize, SymbolizeWithDemanglingStackConsumption) { - Foo::func(100); - int stack_consumed; - const char* symbol; - - symbol = SymbolizeStackConsumption((void *)(&Foo::func), &stack_consumed); - - EXPECT_STREQ("Foo::func()", symbol); - EXPECT_GT(stack_consumed, 0); - EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); -} -#endif - -#endif // HAVE_SIGALTSTACK - -// x86 specific tests. Uses some inline assembler. -extern "C" { -inline void* always_inline inline_func() { - void *pc = NULL; -#ifdef TEST_X86_32_AND_64 - __asm__ __volatile__("call 1f; 1: pop %0" : "=r"(pc)); -#endif - return pc; -} - -void* ATTRIBUTE_NOINLINE non_inline_func(); -void* ATTRIBUTE_NOINLINE non_inline_func() { - void *pc = NULL; -#ifdef TEST_X86_32_AND_64 - __asm__ __volatile__("call 1f; 1: pop %0" : "=r"(pc)); -#endif - return pc; -} - -static void ATTRIBUTE_NOINLINE TestWithPCInsideNonInlineFunction() { -#if defined(TEST_X86_32_AND_64) && defined(HAVE_ATTRIBUTE_NOINLINE) - void *pc = non_inline_func(); - const char *symbol = TrySymbolize(pc); - CHECK(symbol != NULL); - CHECK_STREQ(symbol, "non_inline_func"); - cout << "Test case TestWithPCInsideNonInlineFunction passed." << endl; -#endif -} - -static void ATTRIBUTE_NOINLINE TestWithPCInsideInlineFunction() { -#if defined(TEST_X86_32_AND_64) && defined(HAVE_ALWAYS_INLINE) - void *pc = inline_func(); // Must be inlined. - const char *symbol = TrySymbolize(pc); - CHECK(symbol != NULL); - CHECK_STREQ(symbol, __FUNCTION__); - cout << "Test case TestWithPCInsideInlineFunction passed." << endl; -#endif -} -} - -// Test with a return address. -static void ATTRIBUTE_NOINLINE TestWithReturnAddress() { -#if defined(HAVE_ATTRIBUTE_NOINLINE) - void *return_address = __builtin_return_address(0); - const char *symbol = TrySymbolize(return_address); - CHECK(symbol != NULL); - CHECK_STREQ(symbol, "main"); - cout << "Test case TestWithReturnAddress passed." << endl; -#endif -} - -# elif defined(OS_WINDOWS) || defined(OS_CYGWIN) - -#ifdef _MSC_VER -#include -#pragma intrinsic(_ReturnAddress) -#endif - -struct Foo { - static void func(int x); -}; - -__declspec(noinline) void Foo::func(int x) { - volatile int a = x; - ++a; -} - -TEST(Symbolize, SymbolizeWithDemangling) { - Foo::func(100); - const char* ret = TrySymbolize((void *)(&Foo::func)); - EXPECT_STREQ("public: static void __cdecl Foo::func(int)", ret); -} - -__declspec(noinline) void TestWithReturnAddress() { - void *return_address = -#ifdef __GNUC__ // Cygwin and MinGW support - __builtin_return_address(0) -#else - _ReturnAddress() -#endif - ; - const char *symbol = TrySymbolize(return_address); - CHECK(symbol != NULL); - CHECK_STREQ(symbol, "main"); - cout << "Test case TestWithReturnAddress passed." << endl; -} -# endif // __ELF__ -#endif // HAVE_STACKTRACE - -int main(int argc, char **argv) { - FLAGS_logtostderr = true; - InitGoogleLogging(argv[0]); - InitGoogleTest(&argc, argv); -#if defined(HAVE_SYMBOLIZE) -# if defined(__ELF__) - // We don't want to get affected by the callback interface, that may be - // used to install some callback function at InitGoogle() time. - InstallSymbolizeCallback(NULL); - - TestWithPCInsideInlineFunction(); - TestWithPCInsideNonInlineFunction(); - TestWithReturnAddress(); - return RUN_ALL_TESTS(); -# elif defined(OS_WINDOWS) || defined(OS_CYGWIN) - TestWithReturnAddress(); - return RUN_ALL_TESTS(); -# else // OS_WINDOWS - printf("PASS (no symbolize_unittest support)\n"); - return 0; -# endif // __ELF__ -#else - printf("PASS (no symbolize support)\n"); - return 0; -#endif // HAVE_SYMBOLIZE -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/utilities.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/utilities.cc deleted file mode 100644 index 6562a543ccd..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/utilities.cc +++ /dev/null @@ -1,384 +0,0 @@ -// Copyright (c) 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Shinichiro Hamaji - -#include "utilities.h" - -#include -#include - -#include -#ifdef HAVE_SYS_TIME_H -# include -#endif -#include -#if defined(HAVE_SYSCALL_H) -#include // for syscall() -#elif defined(HAVE_SYS_SYSCALL_H) -#include // for syscall() -#endif -#ifdef HAVE_SYSLOG_H -# include -#endif -#ifdef HAVE_UNISTD_H -# include // For geteuid. -#endif -#ifdef HAVE_PWD_H -# include -#endif - -#include "base/googleinit.h" - -using std::string; - -_START_GOOGLE_NAMESPACE_ - -static const char* g_program_invocation_short_name = NULL; -static pthread_t g_main_thread_id; - -_END_GOOGLE_NAMESPACE_ - -// The following APIs are all internal. -#ifdef HAVE_STACKTRACE - -#include "stacktrace.h" -#include "symbolize.h" -#include "base/commandlineflags.h" - -GLOG_DEFINE_bool(symbolize_stacktrace, true, - "Symbolize the stack trace in the tombstone"); - -_START_GOOGLE_NAMESPACE_ - -typedef void DebugWriter(const char*, void*); - -// The %p field width for printf() functions is two characters per byte. -// For some environments, add two extra bytes for the leading "0x". -static const int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*); - -static void DebugWriteToStderr(const char* data, void *) { - // This one is signal-safe. - if (write(STDERR_FILENO, data, strlen(data)) < 0) { - // Ignore errors. - } -} - -static void DebugWriteToString(const char* data, void *arg) { - reinterpret_cast(arg)->append(data); -} - -#ifdef HAVE_SYMBOLIZE -// Print a program counter and its symbol name. -static void DumpPCAndSymbol(DebugWriter *writerfn, void *arg, void *pc, - const char * const prefix) { - char tmp[1024]; - const char *symbol = "(unknown)"; - // Symbolizes the previous address of pc because pc may be in the - // next function. The overrun happens when the function ends with - // a call to a function annotated noreturn (e.g. CHECK). - if (Symbolize(reinterpret_cast(pc) - 1, tmp, sizeof(tmp))) { - symbol = tmp; - } - char buf[1024]; - snprintf(buf, sizeof(buf), "%s@ %*p %s\n", - prefix, kPrintfPointerFieldWidth, pc, symbol); - writerfn(buf, arg); -} -#endif - -static void DumpPC(DebugWriter *writerfn, void *arg, void *pc, - const char * const prefix) { - char buf[100]; - snprintf(buf, sizeof(buf), "%s@ %*p\n", - prefix, kPrintfPointerFieldWidth, pc); - writerfn(buf, arg); -} - -// Dump current stack trace as directed by writerfn -static void DumpStackTrace(int skip_count, DebugWriter *writerfn, void *arg) { - // Print stack trace - void* stack[32]; - int depth = GetStackTrace(stack, ARRAYSIZE(stack), skip_count+1); - for (int i = 0; i < depth; i++) { -#if defined(HAVE_SYMBOLIZE) - if (FLAGS_symbolize_stacktrace) { - DumpPCAndSymbol(writerfn, arg, stack[i], " "); - } else { - DumpPC(writerfn, arg, stack[i], " "); - } -#else - DumpPC(writerfn, arg, stack[i], " "); -#endif - } -} - -static void DumpStackTraceAndExit() { - DumpStackTrace(1, DebugWriteToStderr, NULL); - - // TODO(hamaji): Use signal instead of sigaction? - if (IsFailureSignalHandlerInstalled()) { - // Set the default signal handler for SIGABRT, to avoid invoking our - // own signal handler installed by InstallFailureSignalHandler(). -#ifdef HAVE_SIGACTION - struct sigaction sig_action; - memset(&sig_action, 0, sizeof(sig_action)); - sigemptyset(&sig_action.sa_mask); - sig_action.sa_handler = SIG_DFL; - sigaction(SIGABRT, &sig_action, NULL); -#elif defined(OS_WINDOWS) - signal(SIGABRT, SIG_DFL); -#endif // HAVE_SIGACTION - } - - abort(); -} - -_END_GOOGLE_NAMESPACE_ - -#endif // HAVE_STACKTRACE - -_START_GOOGLE_NAMESPACE_ - -namespace glog_internal_namespace_ { - -const char* ProgramInvocationShortName() { - if (g_program_invocation_short_name != NULL) { - return g_program_invocation_short_name; - } else { - // TODO(hamaji): Use /proc/self/cmdline and so? - return "UNKNOWN"; - } -} - -bool IsGoogleLoggingInitialized() { - return g_program_invocation_short_name != NULL; -} - -bool is_default_thread() { - if (g_program_invocation_short_name == NULL) { - // InitGoogleLogging() not yet called, so unlikely to be in a different - // thread - return true; - } else { - return pthread_equal(pthread_self(), g_main_thread_id); - } -} - -#ifdef OS_WINDOWS -struct timeval { - long tv_sec, tv_usec; -}; - -// Based on: http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/os_win32.c&q=GetSystemTimeAsFileTime%20license:bsd -// See COPYING for copyright information. -static int gettimeofday(struct timeval *tv, void* tz) { -#define EPOCHFILETIME (116444736000000000ULL) - FILETIME ft; - LARGE_INTEGER li; - uint64 tt; - - GetSystemTimeAsFileTime(&ft); - li.LowPart = ft.dwLowDateTime; - li.HighPart = ft.dwHighDateTime; - tt = (li.QuadPart - EPOCHFILETIME) / 10; - tv->tv_sec = tt / 1000000; - tv->tv_usec = tt % 1000000; - - return 0; -} -#endif - -int64 CycleClock_Now() { - // TODO(hamaji): temporary impementation - it might be too slow. - struct timeval tv; - gettimeofday(&tv, NULL); - return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; -} - -int64 UsecToCycles(int64 usec) { - return usec; -} - -WallTime WallTime_Now() { - // Now, cycle clock is retuning microseconds since the epoch. - return CycleClock_Now() * 0.000001; -} - -static int32 g_main_thread_pid = getpid(); -int32 GetMainThreadPid() { - return g_main_thread_pid; -} - -bool PidHasChanged() { - int32 pid = getpid(); - if (g_main_thread_pid == pid) { - return false; - } - g_main_thread_pid = pid; - return true; -} - -pid_t GetTID() { - // On Linux and MacOSX, we try to use gettid(). -#if defined OS_LINUX || defined OS_MACOSX -#ifndef __NR_gettid -#ifdef OS_MACOSX -#define __NR_gettid SYS_gettid -#elif ! defined __i386__ -#error "Must define __NR_gettid for non-x86 platforms" -#else -#define __NR_gettid 224 -#endif -#endif - static bool lacks_gettid = false; - if (!lacks_gettid) { - pid_t tid = syscall(__NR_gettid); - if (tid != -1) { - return tid; - } - // Technically, this variable has to be volatile, but there is a small - // performance penalty in accessing volatile variables and there should - // not be any serious adverse effect if a thread does not immediately see - // the value change to "true". - lacks_gettid = true; - } -#endif // OS_LINUX || OS_MACOSX - - // If gettid() could not be used, we use one of the following. -#if defined OS_LINUX - return getpid(); // Linux: getpid returns thread ID when gettid is absent -#elif defined OS_WINDOWS && !defined OS_CYGWIN - return GetCurrentThreadId(); -#else - // If none of the techniques above worked, we use pthread_self(). - return (pid_t)(uintptr_t)pthread_self(); -#endif -} - -const char* const_basename(const char* filepath) { - const char* base = strrchr(filepath, '/'); -#ifdef OS_WINDOWS // Look for either path separator in Windows - if (!base) - base = strrchr(filepath, '\\'); -#endif - return base ? (base+1) : filepath; -} - -static string g_my_user_name; -const string& MyUserName() { - return g_my_user_name; -} -static void MyUserNameInitializer() { - // TODO(hamaji): Probably this is not portable. -#if defined(OS_WINDOWS) - const char* user = getenv("USERNAME"); -#else - const char* user = getenv("USER"); -#endif - if (user != NULL) { - g_my_user_name = user; - } else { -#if defined(HAVE_PWD_H) && defined(HAVE_UNISTD_H) - struct passwd pwd; - struct passwd* result = NULL; - char buffer[1024] = {'\0'}; - uid_t uid = geteuid(); - int pwuid_res = getpwuid_r(uid, &pwd, buffer, sizeof(buffer), &result); - if (pwuid_res == 0) { - g_my_user_name = pwd.pw_name; - } else { - snprintf(buffer, sizeof(buffer), "uid%d", uid); - g_my_user_name = buffer; - } -#endif - if (g_my_user_name.empty()) { - g_my_user_name = "invalid-user"; - } - } - -} -REGISTER_MODULE_INITIALIZER(utilities, MyUserNameInitializer()); - -#ifdef HAVE_STACKTRACE -void DumpStackTraceToString(string* stacktrace) { - DumpStackTrace(1, DebugWriteToString, stacktrace); -} -#endif - -// We use an atomic operation to prevent problems with calling CrashReason -// from inside the Mutex implementation (potentially through RAW_CHECK). -static const CrashReason* g_reason = 0; - -void SetCrashReason(const CrashReason* r) { - sync_val_compare_and_swap(&g_reason, - reinterpret_cast(0), - r); -} - -void InitGoogleLoggingUtilities(const char* argv0) { - CHECK(!IsGoogleLoggingInitialized()) - << "You called InitGoogleLogging() twice!"; - const char* slash = strrchr(argv0, '/'); -#ifdef OS_WINDOWS - if (!slash) slash = strrchr(argv0, '\\'); -#endif - g_program_invocation_short_name = slash ? slash + 1 : argv0; - g_main_thread_id = pthread_self(); - -#ifdef HAVE_STACKTRACE - InstallFailureFunction(&DumpStackTraceAndExit); -#endif -} - -void ShutdownGoogleLoggingUtilities() { - CHECK(IsGoogleLoggingInitialized()) - << "You called ShutdownGoogleLogging() without calling InitGoogleLogging() first!"; - g_program_invocation_short_name = NULL; -#ifdef HAVE_SYSLOG_H - closelog(); -#endif -} - -} // namespace glog_internal_namespace_ - -_END_GOOGLE_NAMESPACE_ - -// Make an implementation of stacktrace compiled. -#ifdef STACKTRACE_H -# include STACKTRACE_H -# if 0 -// For include scanners which can't handle macro expansions. -# include "stacktrace_libunwind-inl.h" -# include "stacktrace_x86-inl.h" -# include "stacktrace_x86_64-inl.h" -# include "stacktrace_powerpc-inl.h" -# include "stacktrace_generic-inl.h" -# endif -#endif diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/utilities.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/utilities.h deleted file mode 100644 index ca21cfb3884..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/utilities.h +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Shinichiro Hamaji -// -// Define utilties for glog internal usage. - -#ifndef UTILITIES_H__ -#define UTILITIES_H__ - -#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) -# define OS_WINDOWS -#elif defined(__CYGWIN__) || defined(__CYGWIN32__) -# define OS_CYGWIN -#elif defined(linux) || defined(__linux) || defined(__linux__) -# ifndef OS_LINUX -# define OS_LINUX -# endif -#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) -# define OS_MACOSX -#elif defined(__FreeBSD__) -# define OS_FREEBSD -#elif defined(__NetBSD__) -# define OS_NETBSD -#elif defined(__OpenBSD__) -# define OS_OPENBSD -#else -// TODO(hamaji): Add other platforms. -#endif - -// printf macros for size_t, in the style of inttypes.h -#ifdef _LP64 -#define __PRIS_PREFIX "z" -#else -#define __PRIS_PREFIX -#endif - -// Use these macros after a % in a printf format string -// to get correct 32/64 bit behavior, like this: -// size_t size = records.size(); -// printf("%"PRIuS"\n", size); - -#define PRIdS __PRIS_PREFIX "d" -#define PRIxS __PRIS_PREFIX "x" -#define PRIuS __PRIS_PREFIX "u" -#define PRIXS __PRIS_PREFIX "X" -#define PRIoS __PRIS_PREFIX "o" - -#include "base/mutex.h" // This must go first so we get _XOPEN_SOURCE - -#include - -#if defined(OS_WINDOWS) -# include "port.h" -#endif - -#include "config.h" -#include "glog/logging.h" - -// There are three different ways we can try to get the stack trace: -// -// 1) The libunwind library. This is still in development, and as a -// separate library adds a new dependency, but doesn't need a frame -// pointer. It also doesn't call malloc. -// -// 2) Our hand-coded stack-unwinder. This depends on a certain stack -// layout, which is used by gcc (and those systems using a -// gcc-compatible ABI) on x86 systems, at least since gcc 2.95. -// It uses the frame pointer to do its work. -// -// 3) The gdb unwinder -- also the one used by the c++ exception code. -// It's obviously well-tested, but has a fatal flaw: it can call -// malloc() from the unwinder. This is a problem because we're -// trying to use the unwinder to instrument malloc(). -// -// 4) The Windows API CaptureStackTrace. -// -// Note: if you add a new implementation here, make sure it works -// correctly when GetStackTrace() is called with max_depth == 0. -// Some code may do that. - -#if defined(HAVE_LIB_UNWIND) -# define STACKTRACE_H "stacktrace_libunwind-inl.h" -#elif !defined(NO_FRAME_POINTER) -# if defined(__i386__) && __GNUC__ >= 2 -# define STACKTRACE_H "stacktrace_x86-inl.h" -# elif defined(__x86_64__) && __GNUC__ >= 2 && HAVE_UNWIND_H -# define STACKTRACE_H "stacktrace_x86_64-inl.h" -# elif (defined(__ppc__) || defined(__PPC__)) && __GNUC__ >= 2 -# define STACKTRACE_H "stacktrace_powerpc-inl.h" -# elif defined(OS_WINDOWS) -# define STACKTRACE_H "stacktrace_windows-inl.h" -# endif -#endif - -#if !defined(STACKTRACE_H) && defined(HAVE_EXECINFO_H) -# define STACKTRACE_H "stacktrace_generic-inl.h" -#endif - -#if defined(STACKTRACE_H) -# define HAVE_STACKTRACE -#endif - -#ifndef HAVE_SYMBOLIZE -// defined by gcc -#if defined(__ELF__) && defined(OS_LINUX) -# define HAVE_SYMBOLIZE -#elif defined(OS_MACOSX) && defined(HAVE_DLADDR) -// Use dladdr to symbolize. -# define HAVE_SYMBOLIZE -#elif defined(OS_WINDOWS) -// Use DbgHelp to symbolize -# define HAVE_SYMBOLIZE -#endif -#endif // !defined(HAVE_SYMBOLIZE) - -#ifndef ARRAYSIZE -// There is a better way, but this is good enough for our purpose. -# define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a))) -#endif - -_START_GOOGLE_NAMESPACE_ - -namespace glog_internal_namespace_ { - -#ifdef HAVE___ATTRIBUTE__ -# define ATTRIBUTE_NOINLINE __attribute__ ((noinline)) -# define HAVE_ATTRIBUTE_NOINLINE -#elif defined(OS_WINDOWS) -# define ATTRIBUTE_NOINLINE __declspec(noinline) -# define HAVE_ATTRIBUTE_NOINLINE -#else -# define ATTRIBUTE_NOINLINE -#endif - -const char* ProgramInvocationShortName(); - -bool IsGoogleLoggingInitialized(); - -bool is_default_thread(); - -int64 CycleClock_Now(); - -int64 UsecToCycles(int64 usec); - -typedef double WallTime; -WallTime WallTime_Now(); - -int32 GetMainThreadPid(); -bool PidHasChanged(); - -pid_t GetTID(); - -const std::string& MyUserName(); - -// Get the part of filepath after the last path separator. -// (Doesn't modify filepath, contrary to basename() in libgen.h.) -const char* const_basename(const char* filepath); - -// Wrapper of __sync_val_compare_and_swap. If the GCC extension isn't -// defined, we try the CPU specific logics (we only support x86 and -// x86_64 for now) first, then use a naive implementation, which has a -// race condition. -template -inline T sync_val_compare_and_swap(T* ptr, T oldval, T newval) { -#if defined(HAVE___SYNC_VAL_COMPARE_AND_SWAP) - return __sync_val_compare_and_swap(ptr, oldval, newval); -#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) - T ret; - __asm__ __volatile__("lock; cmpxchg %1, (%2);" - :"=a"(ret) - // GCC may produces %sil or %dil for - // constraint "r", but some of apple's gas - // dosn't know the 8 bit registers. - // We use "q" to avoid these registers. - :"q"(newval), "q"(ptr), "a"(oldval) - :"memory", "cc"); - return ret; -#else - T ret = *ptr; - if (ret == oldval) { - *ptr = newval; - } - return ret; -#endif -} - -void DumpStackTraceToString(std::string* stacktrace); - -struct CrashReason { - CrashReason() : filename(0), line_number(0), message(0), depth(0) {} - - const char* filename; - int line_number; - const char* message; - - // We'll also store a bit of stack trace context at the time of crash as - // it may not be available later on. - void* stack[32]; - int depth; -}; - -void SetCrashReason(const CrashReason* r); - -void InitGoogleLoggingUtilities(const char* argv0); -void ShutdownGoogleLoggingUtilities(); - -} // namespace glog_internal_namespace_ - -_END_GOOGLE_NAMESPACE_ - -using namespace GOOGLE_NAMESPACE::glog_internal_namespace_; - -#endif // UTILITIES_H__ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/utilities_unittest.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/utilities_unittest.cc deleted file mode 100644 index 38e847dfbf7..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/utilities_unittest.cc +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Shinichiro Hamaji -#include "utilities.h" -#include "googletest.h" -#include "glog/logging.h" - -#ifdef HAVE_LIB_GFLAGS -#include -using namespace GFLAGS_NAMESPACE; -#endif - -using namespace GOOGLE_NAMESPACE; - -TEST(utilities, sync_val_compare_and_swap) { - bool now_entering = false; - EXPECT_FALSE(sync_val_compare_and_swap(&now_entering, false, true)); - EXPECT_TRUE(sync_val_compare_and_swap(&now_entering, false, true)); - EXPECT_TRUE(sync_val_compare_and_swap(&now_entering, false, true)); -} - -TEST(utilities, InitGoogleLoggingDeathTest) { - ASSERT_DEATH(InitGoogleLogging("foobar"), ""); -} - -int main(int argc, char **argv) { - InitGoogleLogging(argv[0]); - InitGoogleTest(&argc, argv); - - CHECK_EQ(RUN_ALL_TESTS(), 0); -} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/vlog_is_on.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/vlog_is_on.cc deleted file mode 100644 index e8fdbae7dcb..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/vlog_is_on.cc +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright (c) 1999, 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Ray Sidney and many others -// -// Broken out from logging.cc by Soren Lassen -// logging_unittest.cc covers the functionality herein - -#include "utilities.h" - -#include -#include -#include -#include -#include -#include "base/commandlineflags.h" -#include "glog/logging.h" -#include "glog/raw_logging.h" -#include "base/googleinit.h" - -// glog doesn't have annotation -#define ANNOTATE_BENIGN_RACE(address, description) - -using std::string; - -GLOG_DEFINE_int32(v, 0, "Show all VLOG(m) messages for m <= this." -" Overridable by --vmodule."); - -GLOG_DEFINE_string(vmodule, "", "per-module verbose level." -" Argument is a comma-separated list of =." -" is a glob pattern, matched against the filename base" -" (that is, name ignoring .cc/.h./-inl.h)." -" overrides any value given by --v."); - -_START_GOOGLE_NAMESPACE_ - -namespace glog_internal_namespace_ { - -// Used by logging_unittests.cc so can't make it static here. -GOOGLE_GLOG_DLL_DECL bool SafeFNMatch_(const char* pattern, - size_t patt_len, - const char* str, - size_t str_len); - -// Implementation of fnmatch that does not need 0-termination -// of arguments and does not allocate any memory, -// but we only support "*" and "?" wildcards, not the "[...]" patterns. -// It's not a static function for the unittest. -GOOGLE_GLOG_DLL_DECL bool SafeFNMatch_(const char* pattern, - size_t patt_len, - const char* str, - size_t str_len) { - size_t p = 0; - size_t s = 0; - while (1) { - if (p == patt_len && s == str_len) return true; - if (p == patt_len) return false; - if (s == str_len) return p+1 == patt_len && pattern[p] == '*'; - if (pattern[p] == str[s] || pattern[p] == '?') { - p += 1; - s += 1; - continue; - } - if (pattern[p] == '*') { - if (p+1 == patt_len) return true; - do { - if (SafeFNMatch_(pattern+(p+1), patt_len-(p+1), str+s, str_len-s)) { - return true; - } - s += 1; - } while (s != str_len); - return false; - } - return false; - } -} - -} // namespace glog_internal_namespace_ - -using glog_internal_namespace_::SafeFNMatch_; - -int32 kLogSiteUninitialized = 1000; - -// List of per-module log levels from FLAGS_vmodule. -// Once created each element is never deleted/modified -// except for the vlog_level: other threads will read VModuleInfo blobs -// w/o locks and we'll store pointers to vlog_level at VLOG locations -// that will never go away. -// We can't use an STL struct here as we wouldn't know -// when it's safe to delete/update it: other threads need to use it w/o locks. -struct VModuleInfo { - string module_pattern; - mutable int32 vlog_level; // Conceptually this is an AtomicWord, but it's - // too much work to use AtomicWord type here - // w/o much actual benefit. - const VModuleInfo* next; -}; - -// This protects the following global variables. -static Mutex vmodule_lock; -// Pointer to head of the VModuleInfo list. -// It's a map from module pattern to logging level for those module(s). -static VModuleInfo* vmodule_list = 0; -// Boolean initialization flag. -static bool inited_vmodule = false; - -// L >= vmodule_lock. -static void VLOG2Initializer() { - vmodule_lock.AssertHeld(); - // Can now parse --vmodule flag and initialize mapping of module-specific - // logging levels. - inited_vmodule = false; - const char* vmodule = FLAGS_vmodule.c_str(); - const char* sep; - VModuleInfo* head = NULL; - VModuleInfo* tail = NULL; - while ((sep = strchr(vmodule, '=')) != NULL) { - string pattern(vmodule, sep - vmodule); - int module_level; - if (sscanf(sep, "=%d", &module_level) == 1) { - VModuleInfo* info = new VModuleInfo; - info->module_pattern = pattern; - info->vlog_level = module_level; - if (head) tail->next = info; - else head = info; - tail = info; - } - // Skip past this entry - vmodule = strchr(sep, ','); - if (vmodule == NULL) break; - vmodule++; // Skip past "," - } - if (head) { // Put them into the list at the head: - tail->next = vmodule_list; - vmodule_list = head; - } - inited_vmodule = true; -} - -// This can be called very early, so we use SpinLock and RAW_VLOG here. -int SetVLOGLevel(const char* module_pattern, int log_level) { - int result = FLAGS_v; - int const pattern_len = strlen(module_pattern); - bool found = false; - { - MutexLock l(&vmodule_lock); // protect whole read-modify-write - for (const VModuleInfo* info = vmodule_list; - info != NULL; info = info->next) { - if (info->module_pattern == module_pattern) { - if (!found) { - result = info->vlog_level; - found = true; - } - info->vlog_level = log_level; - } else if (!found && - SafeFNMatch_(info->module_pattern.c_str(), - info->module_pattern.size(), - module_pattern, pattern_len)) { - result = info->vlog_level; - found = true; - } - } - if (!found) { - VModuleInfo* info = new VModuleInfo; - info->module_pattern = module_pattern; - info->vlog_level = log_level; - info->next = vmodule_list; - vmodule_list = info; - } - } - RAW_VLOG(1, "Set VLOG level for \"%s\" to %d", module_pattern, log_level); - return result; -} - -// NOTE: Individual VLOG statements cache the integer log level pointers. -// NOTE: This function must not allocate memory or require any locks. -bool InitVLOG3__(int32** site_flag, int32* site_default, - const char* fname, int32 verbose_level) { - MutexLock l(&vmodule_lock); - bool read_vmodule_flag = inited_vmodule; - if (!read_vmodule_flag) { - VLOG2Initializer(); - } - - // protect the errno global in case someone writes: - // VLOG(..) << "The last error was " << strerror(errno) - int old_errno = errno; - - // site_default normally points to FLAGS_v - int32* site_flag_value = site_default; - - // Get basename for file - const char* base = strrchr(fname, '/'); - base = base ? (base+1) : fname; - const char* base_end = strchr(base, '.'); - size_t base_length = base_end ? size_t(base_end - base) : strlen(base); - - // Trim out trailing "-inl" if any - if (base_length >= 4 && (memcmp(base+base_length-4, "-inl", 4) == 0)) { - base_length -= 4; - } - - // TODO: Trim out _unittest suffix? Perhaps it is better to have - // the extra control and just leave it there. - - // find target in vector of modules, replace site_flag_value with - // a module-specific verbose level, if any. - for (const VModuleInfo* info = vmodule_list; - info != NULL; info = info->next) { - if (SafeFNMatch_(info->module_pattern.c_str(), info->module_pattern.size(), - base, base_length)) { - site_flag_value = &info->vlog_level; - // value at info->vlog_level is now what controls - // the VLOG at the caller site forever - break; - } - } - - // Cache the vlog value pointer if --vmodule flag has been parsed. - ANNOTATE_BENIGN_RACE(site_flag, - "*site_flag may be written by several threads," - " but the value will be the same"); - if (read_vmodule_flag) *site_flag = site_flag_value; - - // restore the errno in case something recoverable went wrong during - // the initialization of the VLOG mechanism (see above note "protect the..") - errno = old_errno; - return *site_flag_value >= verbose_level; -} - -_END_GOOGLE_NAMESPACE_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/log_severity.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/log_severity.h deleted file mode 100644 index 22a4191ab8b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/log_severity.h +++ /dev/null @@ -1,96 +0,0 @@ -// This file is automatically generated from src/glog/log_severity.h -// using src/windows/preprocess.sh. -// DO NOT EDIT! - -// Copyright (c) 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef BASE_LOG_SEVERITY_H__ -#define BASE_LOG_SEVERITY_H__ - -// Annoying stuff for windows -- makes sure clients can import these functions -#ifndef GOOGLE_GLOG_DLL_DECL -# if defined(_WIN32) && !defined(__CYGWIN__) -# define GOOGLE_GLOG_DLL_DECL __declspec(dllimport) -# else -# define GOOGLE_GLOG_DLL_DECL -# endif -#endif - -// Variables of type LogSeverity are widely taken to lie in the range -// [0, NUM_SEVERITIES-1]. Be careful to preserve this assumption if -// you ever need to change their values or add a new severity. -typedef int LogSeverity; - -const int GLOG_INFO = 0, GLOG_WARNING = 1, GLOG_ERROR = 2, GLOG_FATAL = 3, - NUM_SEVERITIES = 4; -#ifndef GLOG_NO_ABBREVIATED_SEVERITIES -# ifdef ERROR -# error ERROR macro is defined. Define GLOG_NO_ABBREVIATED_SEVERITIES before including logging.h. See the document for detail. -# endif -const int INFO = GLOG_INFO, WARNING = GLOG_WARNING, - ERROR = GLOG_ERROR, FATAL = GLOG_FATAL; -#endif - -// DFATAL is FATAL in debug mode, ERROR in normal mode -#ifdef NDEBUG -#define DFATAL_LEVEL ERROR -#else -#define DFATAL_LEVEL FATAL -#endif - -extern GOOGLE_GLOG_DLL_DECL const char* const LogSeverityNames[NUM_SEVERITIES]; - -// NDEBUG usage helpers related to (RAW_)DCHECK: -// -// DEBUG_MODE is for small !NDEBUG uses like -// if (DEBUG_MODE) foo.CheckThatFoo(); -// instead of substantially more verbose -// #ifndef NDEBUG -// foo.CheckThatFoo(); -// #endif -// -// IF_DEBUG_MODE is for small !NDEBUG uses like -// IF_DEBUG_MODE( string error; ) -// DCHECK(Foo(&error)) << error; -// instead of substantially more verbose -// #ifndef NDEBUG -// string error; -// DCHECK(Foo(&error)) << error; -// #endif -// -#ifdef NDEBUG -enum { DEBUG_MODE = 0 }; -#define IF_DEBUG_MODE(x) -#else -enum { DEBUG_MODE = 1 }; -#define IF_DEBUG_MODE(x) x -#endif - -#endif // BASE_LOG_SEVERITY_H__ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/logging.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/logging.h deleted file mode 100755 index 3681fa3fcc4..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/logging.h +++ /dev/null @@ -1,1666 +0,0 @@ -// This file is automatically generated from src/glog/logging.h.in -// using src/windows/preprocess.sh. -// DO NOT EDIT! - -// Copyright (c) 1999, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Ray Sidney -// -// This file contains #include information about logging-related stuff. -// Pretty much everybody needs to #include this file so that they can -// log various happenings. -// -#ifndef _LOGGING_H_ -#define _LOGGING_H_ - -#include -#include -#include -#include -#include -#include -#include -#if 0 -# include -#endif -#include - -#if defined(_MSC_VER) -#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \ - __pragma(warning(disable:n)) -#define GLOG_MSVC_POP_WARNING() __pragma(warning(pop)) -#else -#define GLOG_MSVC_PUSH_DISABLE_WARNING(n) -#define GLOG_MSVC_POP_WARNING() -#endif - -// Annoying stuff for windows -- makes sure clients can import these functions -#ifndef GOOGLE_GLOG_DLL_DECL -# if defined(_WIN32) && !defined(__CYGWIN__) -# define GOOGLE_GLOG_DLL_DECL __declspec(dllimport) -# else -# define GOOGLE_GLOG_DLL_DECL -# endif -#endif - -// We care a lot about number of bits things take up. Unfortunately, -// systems define their bit-specific ints in a lot of different ways. -// We use our own way, and have a typedef to get there. -// Note: these commands below may look like "#if 1" or "#if 0", but -// that's because they were constructed that way at ./configure time. -// Look at logging.h.in to see how they're calculated (based on your config). -#if 0 -#include // the normal place uint16_t is defined -#endif -#if 0 -#include // the normal place u_int16_t is defined -#endif -#if 0 -#include // a third place for uint16_t or u_int16_t -#endif - -#if 0 -#include -#endif - -namespace google { - -#if 0 // the C99 format -typedef int32_t int32; -typedef uint32_t uint32; -typedef int64_t int64; -typedef uint64_t uint64; -#elif 0 // the BSD format -typedef int32_t int32; -typedef u_int32_t uint32; -typedef int64_t int64; -typedef u_int64_t uint64; -#elif 1 // the windows (vc7) format -typedef __int32 int32; -typedef unsigned __int32 uint32; -typedef __int64 int64; -typedef unsigned __int64 uint64; -#else -#error Do not know how to define a 32-bit integer quantity on your system -#endif - -} - -// The global value of GOOGLE_STRIP_LOG. All the messages logged to -// LOG(XXX) with severity less than GOOGLE_STRIP_LOG will not be displayed. -// If it can be determined at compile time that the message will not be -// printed, the statement will be compiled out. -// -// Example: to strip out all INFO and WARNING messages, use the value -// of 2 below. To make an exception for WARNING messages from a single -// file, add "#define GOOGLE_STRIP_LOG 1" to that file _before_ including -// base/logging.h -#ifndef GOOGLE_STRIP_LOG -#define GOOGLE_STRIP_LOG 0 -#endif - -// GCC can be told that a certain branch is not likely to be taken (for -// instance, a CHECK failure), and use that information in static analysis. -// Giving it this information can help it optimize for the common case in -// the absence of better information (ie. -fprofile-arcs). -// -#ifndef GOOGLE_PREDICT_BRANCH_NOT_TAKEN -#if 0 -#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) (__builtin_expect(x, 0)) -#else -#define GOOGLE_PREDICT_BRANCH_NOT_TAKEN(x) x -#endif -#endif - -#ifndef GOOGLE_PREDICT_FALSE -#if 0 -#define GOOGLE_PREDICT_FALSE(x) (__builtin_expect(x, 0)) -#else -#define GOOGLE_PREDICT_FALSE(x) x -#endif -#endif - -#ifndef GOOGLE_PREDICT_TRUE -#if 0 -#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) -#else -#define GOOGLE_PREDICT_TRUE(x) x -#endif -#endif - - -// Make a bunch of macros for logging. The way to log things is to stream -// things to LOG(). E.g., -// -// LOG(INFO) << "Found " << num_cookies << " cookies"; -// -// You can capture log messages in a string, rather than reporting them -// immediately: -// -// vector errors; -// LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num; -// -// This pushes back the new error onto 'errors'; if given a NULL pointer, -// it reports the error via LOG(ERROR). -// -// You can also do conditional logging: -// -// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; -// -// You can also do occasional logging (log every n'th occurrence of an -// event): -// -// LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie"; -// -// The above will cause log messages to be output on the 1st, 11th, 21st, ... -// times it is executed. Note that the special google::COUNTER value is used -// to identify which repetition is happening. -// -// You can also do occasional conditional logging (log every n'th -// occurrence of an event, when condition is satisfied): -// -// LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER -// << "th big cookie"; -// -// You can log messages the first N times your code executes a line. E.g. -// -// LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie"; -// -// Outputs log messages for the first 20 times it is executed. -// -// Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available. -// These log to syslog as well as to the normal logs. If you use these at -// all, you need to be aware that syslog can drastically reduce performance, -// especially if it is configured for remote logging! Don't use these -// unless you fully understand this and have a concrete need to use them. -// Even then, try to minimize your use of them. -// -// There are also "debug mode" logging macros like the ones above: -// -// DLOG(INFO) << "Found cookies"; -// -// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; -// -// DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie"; -// -// All "debug mode" logging is compiled away to nothing for non-debug mode -// compiles. -// -// We also have -// -// LOG_ASSERT(assertion); -// DLOG_ASSERT(assertion); -// -// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion; -// -// There are "verbose level" logging macros. They look like -// -// VLOG(1) << "I'm printed when you run the program with --v=1 or more"; -// VLOG(2) << "I'm printed when you run the program with --v=2 or more"; -// -// These always log at the INFO log level (when they log at all). -// The verbose logging can also be turned on module-by-module. For instance, -// --vmodule=mapreduce=2,file=1,gfs*=3 --v=0 -// will cause: -// a. VLOG(2) and lower messages to be printed from mapreduce.{h,cc} -// b. VLOG(1) and lower messages to be printed from file.{h,cc} -// c. VLOG(3) and lower messages to be printed from files prefixed with "gfs" -// d. VLOG(0) and lower messages to be printed from elsewhere -// -// The wildcarding functionality shown by (c) supports both '*' (match -// 0 or more characters) and '?' (match any single character) wildcards. -// -// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as -// -// if (VLOG_IS_ON(2)) { -// // do some logging preparation and logging -// // that can't be accomplished with just VLOG(2) << ...; -// } -// -// There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level" -// condition macros for sample cases, when some extra computation and -// preparation for logs is not needed. -// VLOG_IF(1, (size > 1024)) -// << "I'm printed when size is more than 1024 and when you run the " -// "program with --v=1 or more"; -// VLOG_EVERY_N(1, 10) -// << "I'm printed every 10th occurrence, and when you run the program " -// "with --v=1 or more. Present occurence is " << google::COUNTER; -// VLOG_IF_EVERY_N(1, (size > 1024), 10) -// << "I'm printed on every 10th occurence of case when size is more " -// " than 1024, when you run the program with --v=1 or more. "; -// "Present occurence is " << google::COUNTER; -// -// The supported severity levels for macros that allow you to specify one -// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL. -// Note that messages of a given severity are logged not only in the -// logfile for that severity, but also in all logfiles of lower severity. -// E.g., a message of severity FATAL will be logged to the logfiles of -// severity FATAL, ERROR, WARNING, and INFO. -// -// There is also the special severity of DFATAL, which logs FATAL in -// debug mode, ERROR in normal mode. -// -// Very important: logging a message at the FATAL severity level causes -// the program to terminate (after the message is logged). -// -// Unless otherwise specified, logs will be written to the filename -// "...log..", followed -// by the date, time, and pid (you can't prevent the date, time, and pid -// from being in the filename). -// -// The logging code takes two flags: -// --v=# set the verbose level -// --logtostderr log all the messages to stderr instead of to logfiles - -// LOG LINE PREFIX FORMAT -// -// Log lines have this form: -// -// Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... -// -// where the fields are defined as follows: -// -// L A single character, representing the log level -// (eg 'I' for INFO) -// mm The month (zero padded; ie May is '05') -// dd The day (zero padded) -// hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds -// threadid The space-padded thread ID as returned by GetTID() -// (this matches the PID on Linux) -// file The file name -// line The line number -// msg The user-supplied message -// -// Example: -// -// I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog -// I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395 -// -// NOTE: although the microseconds are useful for comparing events on -// a single machine, clocks on different machines may not be well -// synchronized. Hence, use caution when comparing the low bits of -// timestamps from different machines. - -#ifndef DECLARE_VARIABLE -#define MUST_UNDEF_GFLAGS_DECLARE_MACROS -#define DECLARE_VARIABLE(type, shorttype, name, tn) \ - namespace fL##shorttype { \ - extern GOOGLE_GLOG_DLL_DECL type FLAGS_##name; \ - } \ - using fL##shorttype::FLAGS_##name - -// bool specialization -#define DECLARE_bool(name) \ - DECLARE_VARIABLE(bool, B, name, bool) - -// int32 specialization -#define DECLARE_int32(name) \ - DECLARE_VARIABLE(google::int32, I, name, int32) - -// Special case for string, because we have to specify the namespace -// std::string, which doesn't play nicely with our FLAG__namespace hackery. -#define DECLARE_string(name) \ - namespace fLS { \ - extern GOOGLE_GLOG_DLL_DECL std::string& FLAGS_##name; \ - } \ - using fLS::FLAGS_##name -#endif - -// Set whether log messages go to stderr instead of logfiles -DECLARE_bool(logtostderr); - -// Set whether log messages go to stderr in addition to logfiles. -DECLARE_bool(alsologtostderr); - -// Set color messages logged to stderr (if supported by terminal). -DECLARE_bool(colorlogtostderr); - -// Log messages at a level >= this flag are automatically sent to -// stderr in addition to log files. -DECLARE_int32(stderrthreshold); - -// Set whether the log prefix should be prepended to each line of output. -DECLARE_bool(log_prefix); - -// Log messages at a level <= this flag are buffered. -// Log messages at a higher level are flushed immediately. -DECLARE_int32(logbuflevel); - -// Sets the maximum number of seconds which logs may be buffered for. -DECLARE_int32(logbufsecs); - -// Log suppression level: messages logged at a lower level than this -// are suppressed. -DECLARE_int32(minloglevel); - -// If specified, logfiles are written into this directory instead of the -// default logging directory. -DECLARE_string(log_dir); - -// Set the log file mode. -DECLARE_int32(logfile_mode); - -// Sets the path of the directory into which to put additional links -// to the log files. -DECLARE_string(log_link); - -DECLARE_int32(v); // in vlog_is_on.cc - -// Sets the maximum log file size (in MB). -DECLARE_int32(max_log_size); - -// Sets whether to avoid logging to the disk if the disk is full. -DECLARE_bool(stop_logging_if_full_disk); - -#ifdef MUST_UNDEF_GFLAGS_DECLARE_MACROS -#undef MUST_UNDEF_GFLAGS_DECLARE_MACROS -#undef DECLARE_VARIABLE -#undef DECLARE_bool -#undef DECLARE_int32 -#undef DECLARE_string -#endif - -// Log messages below the GOOGLE_STRIP_LOG level will be compiled away for -// security reasons. See LOG(severtiy) below. - -// A few definitions of macros that don't generate much code. Since -// LOG(INFO) and its ilk are used all over our code, it's -// better to have compact code for these operations. - -#if GOOGLE_STRIP_LOG == 0 -#define COMPACT_GOOGLE_LOG_INFO google::LogMessage( \ - __FILE__, __LINE__) -#define LOG_TO_STRING_INFO(message) google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_INFO, message) -#else -#define COMPACT_GOOGLE_LOG_INFO google::NullStream() -#define LOG_TO_STRING_INFO(message) google::NullStream() -#endif - -#if GOOGLE_STRIP_LOG <= 1 -#define COMPACT_GOOGLE_LOG_WARNING google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_WARNING) -#define LOG_TO_STRING_WARNING(message) google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_WARNING, message) -#else -#define COMPACT_GOOGLE_LOG_WARNING google::NullStream() -#define LOG_TO_STRING_WARNING(message) google::NullStream() -#endif - -#if GOOGLE_STRIP_LOG <= 2 -#define COMPACT_GOOGLE_LOG_ERROR google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_ERROR) -#define LOG_TO_STRING_ERROR(message) google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_ERROR, message) -#else -#define COMPACT_GOOGLE_LOG_ERROR google::NullStream() -#define LOG_TO_STRING_ERROR(message) google::NullStream() -#endif - -#if GOOGLE_STRIP_LOG <= 3 -#define COMPACT_GOOGLE_LOG_FATAL google::LogMessageFatal( \ - __FILE__, __LINE__) -#define LOG_TO_STRING_FATAL(message) google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_FATAL, message) -#else -#define COMPACT_GOOGLE_LOG_FATAL google::NullStreamFatal() -#define LOG_TO_STRING_FATAL(message) google::NullStreamFatal() -#endif - -#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) -#define DCHECK_IS_ON() 0 -#else -#define DCHECK_IS_ON() 1 -#endif - -// For DFATAL, we want to use LogMessage (as opposed to -// LogMessageFatal), to be consistent with the original behavior. -#if !DCHECK_IS_ON() -#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR -#elif GOOGLE_STRIP_LOG <= 3 -#define COMPACT_GOOGLE_LOG_DFATAL google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_FATAL) -#else -#define COMPACT_GOOGLE_LOG_DFATAL google::NullStreamFatal() -#endif - -#define GOOGLE_LOG_INFO(counter) google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, counter, &google::LogMessage::SendToLog) -#define SYSLOG_INFO(counter) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_INFO, counter, \ - &google::LogMessage::SendToSyslogAndLog) -#define GOOGLE_LOG_WARNING(counter) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, counter, \ - &google::LogMessage::SendToLog) -#define SYSLOG_WARNING(counter) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_WARNING, counter, \ - &google::LogMessage::SendToSyslogAndLog) -#define GOOGLE_LOG_ERROR(counter) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, counter, \ - &google::LogMessage::SendToLog) -#define SYSLOG_ERROR(counter) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, counter, \ - &google::LogMessage::SendToSyslogAndLog) -#define GOOGLE_LOG_FATAL(counter) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, counter, \ - &google::LogMessage::SendToLog) -#define SYSLOG_FATAL(counter) \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_FATAL, counter, \ - &google::LogMessage::SendToSyslogAndLog) -#define GOOGLE_LOG_DFATAL(counter) \ - google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \ - &google::LogMessage::SendToLog) -#define SYSLOG_DFATAL(counter) \ - google::LogMessage(__FILE__, __LINE__, google::DFATAL_LEVEL, counter, \ - &google::LogMessage::SendToSyslogAndLog) - -#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) || defined(__CYGWIN32__) -// A very useful logging macro to log windows errors: -#define LOG_SYSRESULT(result) \ - if (FAILED(HRESULT_FROM_WIN32(result))) { \ - LPSTR message = NULL; \ - LPSTR msg = reinterpret_cast(&message); \ - DWORD message_length = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | \ - FORMAT_MESSAGE_FROM_SYSTEM, \ - 0, result, 0, msg, 100, NULL); \ - if (message_length > 0) { \ - google::LogMessage(__FILE__, __LINE__, google::GLOG_ERROR, 0, \ - &google::LogMessage::SendToLog).stream() \ - << reinterpret_cast(message); \ - LocalFree(message); \ - } \ - } -#endif - -// We use the preprocessor's merging operator, "##", so that, e.g., -// LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny -// subtle difference between ostream member streaming functions (e.g., -// ostream::operator<<(int) and ostream non-member streaming functions -// (e.g., ::operator<<(ostream&, string&): it turns out that it's -// impossible to stream something like a string directly to an unnamed -// ostream. We employ a neat hack by calling the stream() member -// function of LogMessage which seems to avoid the problem. -#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream() -#define SYSLOG(severity) SYSLOG_ ## severity(0).stream() - -namespace google { - -// They need the definitions of integer types. -#include "glog/log_severity.h" -#include "glog/vlog_is_on.h" - -// Initialize google's logging library. You will see the program name -// specified by argv0 in log outputs. -GOOGLE_GLOG_DLL_DECL void InitGoogleLogging(const char* argv0); - -// Shutdown google's logging library. -GOOGLE_GLOG_DLL_DECL void ShutdownGoogleLogging(); - -// Install a function which will be called after LOG(FATAL). -GOOGLE_GLOG_DLL_DECL void InstallFailureFunction(void (*fail_func)()); - -class LogSink; // defined below - -// If a non-NULL sink pointer is given, we push this message to that sink. -// For LOG_TO_SINK we then do normal LOG(severity) logging as well. -// This is useful for capturing messages and passing/storing them -// somewhere more specific than the global log of the process. -// Argument types: -// LogSink* sink; -// LogSeverity severity; -// The cast is to disambiguate NULL arguments. -#define LOG_TO_SINK(sink, severity) \ - google::LogMessage( \ - __FILE__, __LINE__, \ - google::GLOG_ ## severity, \ - static_cast(sink), true).stream() -#define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \ - google::LogMessage( \ - __FILE__, __LINE__, \ - google::GLOG_ ## severity, \ - static_cast(sink), false).stream() - -// If a non-NULL string pointer is given, we write this message to that string. -// We then do normal LOG(severity) logging as well. -// This is useful for capturing messages and storing them somewhere more -// specific than the global log of the process. -// Argument types: -// string* message; -// LogSeverity severity; -// The cast is to disambiguate NULL arguments. -// NOTE: LOG(severity) expands to LogMessage().stream() for the specified -// severity. -#define LOG_TO_STRING(severity, message) \ - LOG_TO_STRING_##severity(static_cast(message)).stream() - -// If a non-NULL pointer is given, we push the message onto the end -// of a vector of strings; otherwise, we report it with LOG(severity). -// This is handy for capturing messages and perhaps passing them back -// to the caller, rather than reporting them immediately. -// Argument types: -// LogSeverity severity; -// vector *outvec; -// The cast is to disambiguate NULL arguments. -#define LOG_STRING(severity, outvec) \ - LOG_TO_STRING_##severity(static_cast*>(outvec)).stream() - -#define LOG_IF(severity, condition) \ - static_cast(0), \ - !(condition) ? (void) 0 : google::LogMessageVoidify() & LOG(severity) -#define SYSLOG_IF(severity, condition) \ - static_cast(0), \ - !(condition) ? (void) 0 : google::LogMessageVoidify() & SYSLOG(severity) - -#define LOG_ASSERT(condition) \ - LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition -#define SYSLOG_ASSERT(condition) \ - SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition - -// CHECK dies with a fatal error if condition is not true. It is *not* -// controlled by DCHECK_IS_ON(), so the check will be executed regardless of -// compilation mode. Therefore, it is safe to do things like: -// CHECK(fp->Write(x) == 4) -#define CHECK(condition) \ - LOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \ - << "Check failed: " #condition " " - -// A container for a string pointer which can be evaluated to a bool - -// true iff the pointer is NULL. -struct CheckOpString { - CheckOpString(std::string* str) : str_(str) { } - // No destructor: if str_ is non-NULL, we're about to LOG(FATAL), - // so there's no point in cleaning up str_. - operator bool() const { - return GOOGLE_PREDICT_BRANCH_NOT_TAKEN(str_ != NULL); - } - std::string* str_; -}; - -// Function is overloaded for integral types to allow static const -// integrals declared in classes and not defined to be used as arguments to -// CHECK* macros. It's not encouraged though. -template -inline const T& GetReferenceableValue(const T& t) { return t; } -inline char GetReferenceableValue(char t) { return t; } -inline unsigned char GetReferenceableValue(unsigned char t) { return t; } -inline signed char GetReferenceableValue(signed char t) { return t; } -inline short GetReferenceableValue(short t) { return t; } -inline unsigned short GetReferenceableValue(unsigned short t) { return t; } -inline int GetReferenceableValue(int t) { return t; } -inline unsigned int GetReferenceableValue(unsigned int t) { return t; } -inline long GetReferenceableValue(long t) { return t; } -inline unsigned long GetReferenceableValue(unsigned long t) { return t; } -inline long long GetReferenceableValue(long long t) { return t; } -inline unsigned long long GetReferenceableValue(unsigned long long t) { - return t; -} - -// This is a dummy class to define the following operator. -struct DummyClassToDefineOperator {}; - -} - -// Define global operator<< to declare using ::operator<<. -// This declaration will allow use to use CHECK macros for user -// defined classes which have operator<< (e.g., stl_logging.h). -inline std::ostream& operator<<( - std::ostream& out, const google::DummyClassToDefineOperator&) { - return out; -} - -namespace google { - -// This formats a value for a failing CHECK_XX statement. Ordinarily, -// it uses the definition for operator<<, with a few special cases below. -template -inline void MakeCheckOpValueString(std::ostream* os, const T& v) { - (*os) << v; -} - -// Overrides for char types provide readable values for unprintable -// characters. -template <> GOOGLE_GLOG_DLL_DECL -void MakeCheckOpValueString(std::ostream* os, const char& v); -template <> GOOGLE_GLOG_DLL_DECL -void MakeCheckOpValueString(std::ostream* os, const signed char& v); -template <> GOOGLE_GLOG_DLL_DECL -void MakeCheckOpValueString(std::ostream* os, const unsigned char& v); - -// Build the error message string. Specify no inlining for code size. -template -std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) - ; - -namespace base { -namespace internal { - -// If "s" is less than base_logging::INFO, returns base_logging::INFO. -// If "s" is greater than base_logging::FATAL, returns -// base_logging::ERROR. Otherwise, returns "s". -LogSeverity NormalizeSeverity(LogSeverity s); - -} // namespace internal - -// A helper class for formatting "expr (V1 vs. V2)" in a CHECK_XX -// statement. See MakeCheckOpString for sample usage. Other -// approaches were considered: use of a template method (e.g., -// base::BuildCheckOpString(exprtext, base::Print, &v1, -// base::Print, &v2), however this approach has complications -// related to volatile arguments and function-pointer arguments). -class GOOGLE_GLOG_DLL_DECL CheckOpMessageBuilder { - public: - // Inserts "exprtext" and " (" to the stream. - explicit CheckOpMessageBuilder(const char *exprtext); - // Deletes "stream_". - ~CheckOpMessageBuilder(); - // For inserting the first variable. - std::ostream* ForVar1() { return stream_; } - // For inserting the second variable (adds an intermediate " vs. "). - std::ostream* ForVar2(); - // Get the result (inserts the closing ")"). - std::string* NewString(); - - private: - std::ostringstream *stream_; -}; - -} // namespace base - -template -std::string* MakeCheckOpString(const T1& v1, const T2& v2, const char* exprtext) { - base::CheckOpMessageBuilder comb(exprtext); - MakeCheckOpValueString(comb.ForVar1(), v1); - MakeCheckOpValueString(comb.ForVar2(), v2); - return comb.NewString(); -} - -// Helper functions for CHECK_OP macro. -// The (int, int) specialization works around the issue that the compiler -// will not instantiate the template version of the function on values of -// unnamed enum type - see comment below. -#define DEFINE_CHECK_OP_IMPL(name, op) \ - template \ - inline std::string* name##Impl(const T1& v1, const T2& v2, \ - const char* exprtext) { \ - if (GOOGLE_PREDICT_TRUE(v1 op v2)) return NULL; \ - else return MakeCheckOpString(v1, v2, exprtext); \ - } \ - inline std::string* name##Impl(int v1, int v2, const char* exprtext) { \ - return name##Impl(v1, v2, exprtext); \ - } - -// We use the full name Check_EQ, Check_NE, etc. in case the file including -// base/logging.h provides its own #defines for the simpler names EQ, NE, etc. -// This happens if, for example, those are used as token names in a -// yacc grammar. -DEFINE_CHECK_OP_IMPL(Check_EQ, ==) // Compilation error with CHECK_EQ(NULL, x)? -DEFINE_CHECK_OP_IMPL(Check_NE, !=) // Use CHECK(x == NULL) instead. -DEFINE_CHECK_OP_IMPL(Check_LE, <=) -DEFINE_CHECK_OP_IMPL(Check_LT, < ) -DEFINE_CHECK_OP_IMPL(Check_GE, >=) -DEFINE_CHECK_OP_IMPL(Check_GT, > ) -#undef DEFINE_CHECK_OP_IMPL - -// Helper macro for binary operators. -// Don't use this macro directly in your code, use CHECK_EQ et al below. - -#if defined(STATIC_ANALYSIS) -// Only for static analysis tool to know that it is equivalent to assert -#define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2)) -#elif DCHECK_IS_ON() -// In debug mode, avoid constructing CheckOpStrings if possible, -// to reduce the overhead of CHECK statments by 2x. -// Real DCHECK-heavy tests have seen 1.5x speedups. - -// The meaning of "string" might be different between now and -// when this macro gets invoked (e.g., if someone is experimenting -// with other string implementations that get defined after this -// file is included). Save the current meaning now and use it -// in the macro. -typedef std::string _Check_string; -#define CHECK_OP_LOG(name, op, val1, val2, log) \ - while (google::_Check_string* _result = \ - google::Check##name##Impl( \ - google::GetReferenceableValue(val1), \ - google::GetReferenceableValue(val2), \ - #val1 " " #op " " #val2)) \ - log(__FILE__, __LINE__, \ - google::CheckOpString(_result)).stream() -#else -// In optimized mode, use CheckOpString to hint to compiler that -// the while condition is unlikely. -#define CHECK_OP_LOG(name, op, val1, val2, log) \ - while (google::CheckOpString _result = \ - google::Check##name##Impl( \ - google::GetReferenceableValue(val1), \ - google::GetReferenceableValue(val2), \ - #val1 " " #op " " #val2)) \ - log(__FILE__, __LINE__, _result).stream() -#endif // STATIC_ANALYSIS, DCHECK_IS_ON() - -#if GOOGLE_STRIP_LOG <= 3 -#define CHECK_OP(name, op, val1, val2) \ - CHECK_OP_LOG(name, op, val1, val2, google::LogMessageFatal) -#else -#define CHECK_OP(name, op, val1, val2) \ - CHECK_OP_LOG(name, op, val1, val2, google::NullStreamFatal) -#endif // STRIP_LOG <= 3 - -// Equality/Inequality checks - compare two values, and log a FATAL message -// including the two values when the result is not as expected. The values -// must have operator<<(ostream, ...) defined. -// -// You may append to the error message like so: -// CHECK_NE(1, 2) << ": The world must be ending!"; -// -// We are very careful to ensure that each argument is evaluated exactly -// once, and that anything which is legal to pass as a function argument is -// legal here. In particular, the arguments may be temporary expressions -// which will end up being destroyed at the end of the apparent statement, -// for example: -// CHECK_EQ(string("abc")[1], 'b'); -// -// WARNING: These don't compile correctly if one of the arguments is a pointer -// and the other is NULL. To work around this, simply static_cast NULL to the -// type of the desired pointer. - -#define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2) -#define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2) -#define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2) -#define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2) -#define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2) -#define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2) - -// Check that the input is non NULL. This very useful in constructor -// initializer lists. - -#define CHECK_NOTNULL(val) \ - google::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val)) - -// Helper functions for string comparisons. -// To avoid bloat, the definitions are in logging.cc. -#define DECLARE_CHECK_STROP_IMPL(func, expected) \ - GOOGLE_GLOG_DLL_DECL std::string* Check##func##expected##Impl( \ - const char* s1, const char* s2, const char* names); -DECLARE_CHECK_STROP_IMPL(strcmp, true) -DECLARE_CHECK_STROP_IMPL(strcmp, false) -DECLARE_CHECK_STROP_IMPL(strcasecmp, true) -DECLARE_CHECK_STROP_IMPL(strcasecmp, false) -#undef DECLARE_CHECK_STROP_IMPL - -// Helper macro for string comparisons. -// Don't use this macro directly in your code, use CHECK_STREQ et al below. -#define CHECK_STROP(func, op, expected, s1, s2) \ - while (google::CheckOpString _result = \ - google::Check##func##expected##Impl((s1), (s2), \ - #s1 " " #op " " #s2)) \ - LOG(FATAL) << *_result.str_ - - -// String (char*) equality/inequality checks. -// CASE versions are case-insensitive. -// -// Note that "s1" and "s2" may be temporary strings which are destroyed -// by the compiler at the end of the current "full expression" -// (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())). - -#define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2) -#define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2) -#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2) -#define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2) - -#define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0]))) -#define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0]))) - -#define CHECK_DOUBLE_EQ(val1, val2) \ - do { \ - CHECK_LE((val1), (val2)+0.000000000000001L); \ - CHECK_GE((val1), (val2)-0.000000000000001L); \ - } while (0) - -#define CHECK_NEAR(val1, val2, margin) \ - do { \ - CHECK_LE((val1), (val2)+(margin)); \ - CHECK_GE((val1), (val2)-(margin)); \ - } while (0) - -// perror()..googly style! -// -// PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and -// CHECK equivalents with the addition that they postpend a description -// of the current state of errno to their output lines. - -#define PLOG(severity) GOOGLE_PLOG(severity, 0).stream() - -#define GOOGLE_PLOG(severity, counter) \ - google::ErrnoLogMessage( \ - __FILE__, __LINE__, google::GLOG_ ## severity, counter, \ - &google::LogMessage::SendToLog) - -#define PLOG_IF(severity, condition) \ - static_cast(0), \ - !(condition) ? (void) 0 : google::LogMessageVoidify() & PLOG(severity) - -// A CHECK() macro that postpends errno if the condition is false. E.g. -// -// if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... } -#define PCHECK(condition) \ - PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN(!(condition))) \ - << "Check failed: " #condition " " - -// A CHECK() macro that lets you assert the success of a function that -// returns -1 and sets errno in case of an error. E.g. -// -// CHECK_ERR(mkdir(path, 0700)); -// -// or -// -// int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename; -#define CHECK_ERR(invocation) \ -PLOG_IF(FATAL, GOOGLE_PREDICT_BRANCH_NOT_TAKEN((invocation) == -1)) \ - << #invocation - -// Use macro expansion to create, for each use of LOG_EVERY_N(), static -// variables with the __LINE__ expansion as part of the variable name. -#define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line) -#define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line - -#define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__) -#define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__) - -#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \ - static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ - ++LOG_OCCURRENCES; \ - if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ - if (LOG_OCCURRENCES_MOD_N == 1) \ - google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_ ## severity, LOG_OCCURRENCES, \ - &what_to_do).stream() - -#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \ - static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ - ++LOG_OCCURRENCES; \ - if (condition && \ - ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \ - google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_ ## severity, LOG_OCCURRENCES, \ - &what_to_do).stream() - -#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \ - static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ - ++LOG_OCCURRENCES; \ - if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ - if (LOG_OCCURRENCES_MOD_N == 1) \ - google::ErrnoLogMessage( \ - __FILE__, __LINE__, google::GLOG_ ## severity, LOG_OCCURRENCES, \ - &what_to_do).stream() - -#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \ - static int LOG_OCCURRENCES = 0; \ - if (LOG_OCCURRENCES <= n) \ - ++LOG_OCCURRENCES; \ - if (LOG_OCCURRENCES <= n) \ - google::LogMessage( \ - __FILE__, __LINE__, google::GLOG_ ## severity, LOG_OCCURRENCES, \ - &what_to_do).stream() - -namespace glog_internal_namespace_ { -template -struct CompileAssert { -}; -struct CrashReason; - -// Returns true if FailureSignalHandler is installed. -// Needs to be exported since it's used by the signalhandler_unittest. -GOOGLE_GLOG_DLL_DECL bool IsFailureSignalHandlerInstalled(); -} // namespace glog_internal_namespace_ - -#define LOG_EVERY_N(severity, n) \ - SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToLog) - -#define SYSLOG_EVERY_N(severity, n) \ - SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToSyslogAndLog) - -#define PLOG_EVERY_N(severity, n) \ - SOME_KIND_OF_PLOG_EVERY_N(severity, (n), google::LogMessage::SendToLog) - -#define LOG_FIRST_N(severity, n) \ - SOME_KIND_OF_LOG_FIRST_N(severity, (n), google::LogMessage::SendToLog) - -#define LOG_IF_EVERY_N(severity, condition, n) \ - SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), google::LogMessage::SendToLog) - -// We want the special COUNTER value available for LOG_EVERY_X()'ed messages -enum PRIVATE_Counter {COUNTER}; - -#ifdef GLOG_NO_ABBREVIATED_SEVERITIES -// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets -// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us -// to keep using this syntax, we define this macro to do the same thing -// as COMPACT_GOOGLE_LOG_ERROR. -#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR -#define SYSLOG_0 SYSLOG_ERROR -#define LOG_TO_STRING_0 LOG_TO_STRING_ERROR -// Needed for LOG_IS_ON(ERROR). -const LogSeverity GLOG_0 = GLOG_ERROR; -#else -// Users may include windows.h after logging.h without -// GLOG_NO_ABBREVIATED_SEVERITIES nor WIN32_LEAN_AND_MEAN. -// For this case, we cannot detect if ERROR is defined before users -// actually use ERROR. Let's make an undefined symbol to warn users. -# define GLOG_ERROR_MSG ERROR_macro_is_defined_Define_GLOG_NO_ABBREVIATED_SEVERITIES_before_including_logging_h_See_the_document_for_detail -# define COMPACT_GOOGLE_LOG_0 GLOG_ERROR_MSG -# define SYSLOG_0 GLOG_ERROR_MSG -# define LOG_TO_STRING_0 GLOG_ERROR_MSG -# define GLOG_0 GLOG_ERROR_MSG -#endif - -// Plus some debug-logging macros that get compiled to nothing for production - -#if DCHECK_IS_ON() - -#define DLOG(severity) LOG(severity) -#define DVLOG(verboselevel) VLOG(verboselevel) -#define DLOG_IF(severity, condition) LOG_IF(severity, condition) -#define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n) -#define DLOG_IF_EVERY_N(severity, condition, n) \ - LOG_IF_EVERY_N(severity, condition, n) -#define DLOG_ASSERT(condition) LOG_ASSERT(condition) - -// debug-only checking. executed if DCHECK_IS_ON(). -#define DCHECK(condition) CHECK(condition) -#define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2) -#define DCHECK_NE(val1, val2) CHECK_NE(val1, val2) -#define DCHECK_LE(val1, val2) CHECK_LE(val1, val2) -#define DCHECK_LT(val1, val2) CHECK_LT(val1, val2) -#define DCHECK_GE(val1, val2) CHECK_GE(val1, val2) -#define DCHECK_GT(val1, val2) CHECK_GT(val1, val2) -#define DCHECK_NOTNULL(val) CHECK_NOTNULL(val) -#define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2) -#define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2) -#define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2) -#define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2) - -#else // !DCHECK_IS_ON() - -#define DLOG(severity) \ - static_cast(0), \ - true ? (void) 0 : google::LogMessageVoidify() & LOG(severity) - -#define DVLOG(verboselevel) \ - static_cast(0), \ - (true || !VLOG_IS_ON(verboselevel)) ? \ - (void) 0 : google::LogMessageVoidify() & LOG(INFO) - -#define DLOG_IF(severity, condition) \ - static_cast(0), \ - (true || !(condition)) ? (void) 0 : google::LogMessageVoidify() & LOG(severity) - -#define DLOG_EVERY_N(severity, n) \ - static_cast(0), \ - true ? (void) 0 : google::LogMessageVoidify() & LOG(severity) - -#define DLOG_IF_EVERY_N(severity, condition, n) \ - static_cast(0), \ - (true || !(condition))? (void) 0 : google::LogMessageVoidify() & LOG(severity) - -#define DLOG_ASSERT(condition) \ - static_cast(0), \ - true ? (void) 0 : LOG_ASSERT(condition) - -// MSVC warning C4127: conditional expression is constant -#define DCHECK(condition) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK(condition) - -#define DCHECK_EQ(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_EQ(val1, val2) - -#define DCHECK_NE(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_NE(val1, val2) - -#define DCHECK_LE(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_LE(val1, val2) - -#define DCHECK_LT(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_LT(val1, val2) - -#define DCHECK_GE(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_GE(val1, val2) - -#define DCHECK_GT(val1, val2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_GT(val1, val2) - -// You may see warnings in release mode if you don't use the return -// value of DCHECK_NOTNULL. Please just use DCHECK for such cases. -#define DCHECK_NOTNULL(val) (val) - -#define DCHECK_STREQ(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_STREQ(str1, str2) - -#define DCHECK_STRCASEEQ(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_STRCASEEQ(str1, str2) - -#define DCHECK_STRNE(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_STRNE(str1, str2) - -#define DCHECK_STRCASENE(str1, str2) \ - GLOG_MSVC_PUSH_DISABLE_WARNING(4127) \ - while (false) \ - GLOG_MSVC_POP_WARNING() CHECK_STRCASENE(str1, str2) - -#endif // DCHECK_IS_ON() - -// Log only in verbose mode. - -#define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel)) - -#define VLOG_IF(verboselevel, condition) \ - LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel)) - -#define VLOG_EVERY_N(verboselevel, n) \ - LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n) - -#define VLOG_IF_EVERY_N(verboselevel, condition, n) \ - LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n) - -namespace base_logging { - -// LogMessage::LogStream is a std::ostream backed by this streambuf. -// This class ignores overflow and leaves two bytes at the end of the -// buffer to allow for a '\n' and '\0'. -class GOOGLE_GLOG_DLL_DECL LogStreamBuf : public std::streambuf { - public: - // REQUIREMENTS: "len" must be >= 2 to account for the '\n' and '\0'. - LogStreamBuf(char *buf, int len) { - setp(buf, buf + len - 2); - } - - // This effectively ignores overflow. - virtual int_type overflow(int_type ch) { - return ch; - } - - // Legacy public ostrstream method. - size_t pcount() const { return pptr() - pbase(); } - char* pbase() const { return std::streambuf::pbase(); } -}; - -} // namespace base_logging - -// -// This class more or less represents a particular log message. You -// create an instance of LogMessage and then stream stuff to it. -// When you finish streaming to it, ~LogMessage is called and the -// full message gets streamed to the appropriate destination. -// -// You shouldn't actually use LogMessage's constructor to log things, -// though. You should use the LOG() macro (and variants thereof) -// above. -class GOOGLE_GLOG_DLL_DECL LogMessage { -public: - enum { - // Passing kNoLogPrefix for the line number disables the - // log-message prefix. Useful for using the LogMessage - // infrastructure as a printing utility. See also the --log_prefix - // flag for controlling the log-message prefix on an - // application-wide basis. - kNoLogPrefix = -1 - }; - - // LogStream inherit from non-DLL-exported class (std::ostrstream) - // and VC++ produces a warning for this situation. - // However, MSDN says "C4275 can be ignored in Microsoft Visual C++ - // 2005 if you are deriving from a type in the Standard C++ Library" - // http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx - // Let's just ignore the warning. -GLOG_MSVC_PUSH_DISABLE_WARNING(4275) - class GOOGLE_GLOG_DLL_DECL LogStream : public std::ostream { -GLOG_MSVC_POP_WARNING() - public: - LogStream(char *buf, int len, int ctr) - : std::ostream(NULL), - streambuf_(buf, len), - ctr_(ctr), - self_(this) { - rdbuf(&streambuf_); - } - - int ctr() const { return ctr_; } - void set_ctr(int ctr) { ctr_ = ctr; } - LogStream* self() const { return self_; } - - // Legacy std::streambuf methods. - size_t pcount() const { return streambuf_.pcount(); } - char* pbase() const { return streambuf_.pbase(); } - char* str() const { return pbase(); } - - private: - LogStream(const LogStream&); - LogStream& operator=(const LogStream&); - base_logging::LogStreamBuf streambuf_; - int ctr_; // Counter hack (for the LOG_EVERY_X() macro) - LogStream *self_; // Consistency check hack - }; - -public: - // icc 8 requires this typedef to avoid an internal compiler error. - typedef void (LogMessage::*SendMethod)(); - - LogMessage(const char* file, int line, LogSeverity severity, int ctr, - SendMethod send_method); - - // Two special constructors that generate reduced amounts of code at - // LOG call sites for common cases. - - // Used for LOG(INFO): Implied are: - // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog. - // - // Using this constructor instead of the more complex constructor above - // saves 19 bytes per call site. - LogMessage(const char* file, int line); - - // Used for LOG(severity) where severity != INFO. Implied - // are: ctr = 0, send_method = &LogMessage::SendToLog - // - // Using this constructor instead of the more complex constructor above - // saves 17 bytes per call site. - LogMessage(const char* file, int line, LogSeverity severity); - - // Constructor to log this message to a specified sink (if not NULL). - // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if - // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise. - LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink, - bool also_send_to_log); - - // Constructor where we also give a vector pointer - // for storing the messages (if the pointer is not NULL). - // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog. - LogMessage(const char* file, int line, LogSeverity severity, - std::vector* outvec); - - // Constructor where we also give a string pointer for storing the - // message (if the pointer is not NULL). Implied are: ctr = 0, - // send_method = &LogMessage::WriteToStringAndLog. - LogMessage(const char* file, int line, LogSeverity severity, - std::string* message); - - // A special constructor used for check failures - LogMessage(const char* file, int line, const CheckOpString& result); - - ~LogMessage(); - - // Flush a buffered message to the sink set in the constructor. Always - // called by the destructor, it may also be called from elsewhere if - // needed. Only the first call is actioned; any later ones are ignored. - void Flush(); - - // An arbitrary limit on the length of a single log message. This - // is so that streaming can be done more efficiently. - static const size_t kMaxLogMessageLen; - - // Theses should not be called directly outside of logging.*, - // only passed as SendMethod arguments to other LogMessage methods: - void SendToLog(); // Actually dispatch to the logs - void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs - - // Call abort() or similar to perform LOG(FATAL) crash. - static void __declspec(noreturn) Fail(); - - std::ostream& stream(); - - int preserved_errno() const; - - // Must be called without the log_mutex held. (L < log_mutex) - static int64 num_messages(int severity); - - struct LogMessageData; - -private: - // Fully internal SendMethod cases: - void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs - void SendToSink(); // Send to sink if provided, do nothing otherwise. - - // Write to string if provided and dispatch to the logs. - void WriteToStringAndLog(); - - void SaveOrSendToLog(); // Save to stringvec if provided, else to logs - - void Init(const char* file, int line, LogSeverity severity, - void (LogMessage::*send_method)()); - - // Used to fill in crash information during LOG(FATAL) failures. - void RecordCrashReason(glog_internal_namespace_::CrashReason* reason); - - // Counts of messages sent at each priority: - static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex - - // We keep the data in a separate struct so that each instance of - // LogMessage uses less stack space. - LogMessageData* allocated_; - LogMessageData* data_; - - friend class LogDestination; - - LogMessage(const LogMessage&); - void operator=(const LogMessage&); -}; - -// This class happens to be thread-hostile because all instances share -// a single data buffer, but since it can only be created just before -// the process dies, we don't worry so much. -class GOOGLE_GLOG_DLL_DECL LogMessageFatal : public LogMessage { - public: - LogMessageFatal(const char* file, int line); - LogMessageFatal(const char* file, int line, const CheckOpString& result); - __declspec(noreturn) ~LogMessageFatal(); -}; - -// A non-macro interface to the log facility; (useful -// when the logging level is not a compile-time constant). -inline void LogAtLevel(int const severity, std::string const &msg) { - LogMessage(__FILE__, __LINE__, severity).stream() << msg; -} - -// A macro alternative of LogAtLevel. New code may want to use this -// version since there are two advantages: 1. this version outputs the -// file name and the line number where this macro is put like other -// LOG macros, 2. this macro can be used as C++ stream. -#define LOG_AT_LEVEL(severity) google::LogMessage(__FILE__, __LINE__, severity).stream() - -// Check if it's compiled in C++11 mode. -// -// GXX_EXPERIMENTAL_CXX0X is defined by gcc and clang up to at least -// gcc-4.7 and clang-3.1 (2011-12-13). __cplusplus was defined to 1 -// in gcc before 4.7 (Crosstool 16) and clang before 3.1, but is -// defined according to the language version in effect thereafter. -// Microsoft Visual Studio 14 (2015) sets __cplusplus==199711 despite -// reasonably good C++11 support, so we set LANG_CXX for it and -// newer versions (_MSC_VER >= 1900). -#if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L || \ - (defined(_MSC_VER) && _MSC_VER >= 1900)) -// Helper for CHECK_NOTNULL(). -// -// In C++11, all cases can be handled by a single function. Since the value -// category of the argument is preserved (also for rvalue references), -// member initializer lists like the one below will compile correctly: -// -// Foo() -// : x_(CHECK_NOTNULL(MethodReturningUniquePtr())) {} -template -T CheckNotNull(const char* file, int line, const char* names, T&& t) { - if (t == nullptr) { - LogMessageFatal(file, line, new std::string(names)); - } - return std::forward(t); -} - -#else - -// A small helper for CHECK_NOTNULL(). -template -T* CheckNotNull(const char *file, int line, const char *names, T* t) { - if (t == NULL) { - LogMessageFatal(file, line, new std::string(names)); - } - return t; -} -#endif - -// Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This -// only works if ostream is a LogStream. If the ostream is not a -// LogStream you'll get an assert saying as much at runtime. -GOOGLE_GLOG_DLL_DECL std::ostream& operator<<(std::ostream &os, - const PRIVATE_Counter&); - - -// Derived class for PLOG*() above. -class GOOGLE_GLOG_DLL_DECL ErrnoLogMessage : public LogMessage { - public: - - ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr, - void (LogMessage::*send_method)()); - - // Postpends ": strerror(errno) [errno]". - ~ErrnoLogMessage(); - - private: - ErrnoLogMessage(const ErrnoLogMessage&); - void operator=(const ErrnoLogMessage&); -}; - - -// This class is used to explicitly ignore values in the conditional -// logging macros. This avoids compiler warnings like "value computed -// is not used" and "statement has no effect". - -class GOOGLE_GLOG_DLL_DECL LogMessageVoidify { - public: - LogMessageVoidify() { } - // This has to be an operator with a precedence lower than << but - // higher than ?: - void operator&(std::ostream&) { } -}; - - -// Flushes all log files that contains messages that are at least of -// the specified severity level. Thread-safe. -GOOGLE_GLOG_DLL_DECL void FlushLogFiles(LogSeverity min_severity); - -// Flushes all log files that contains messages that are at least of -// the specified severity level. Thread-hostile because it ignores -// locking -- used for catastrophic failures. -GOOGLE_GLOG_DLL_DECL void FlushLogFilesUnsafe(LogSeverity min_severity); - -// -// Set the destination to which a particular severity level of log -// messages is sent. If base_filename is "", it means "don't log this -// severity". Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetLogDestination(LogSeverity severity, - const char* base_filename); - -// -// Set the basename of the symlink to the latest log file at a given -// severity. If symlink_basename is empty, do not make a symlink. If -// you don't call this function, the symlink basename is the -// invocation name of the program. Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetLogSymlink(LogSeverity severity, - const char* symlink_basename); - -// -// Used to send logs to some other kind of destination -// Users should subclass LogSink and override send to do whatever they want. -// Implementations must be thread-safe because a shared instance will -// be called from whichever thread ran the LOG(XXX) line. -class GOOGLE_GLOG_DLL_DECL LogSink { - public: - virtual ~LogSink(); - - // Sink's logging logic (message_len is such as to exclude '\n' at the end). - // This method can't use LOG() or CHECK() as logging system mutex(s) are held - // during this call. - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, - const struct ::tm* tm_time, - const char* message, size_t message_len) = 0; - - // Redefine this to implement waiting for - // the sink's logging logic to complete. - // It will be called after each send() returns, - // but before that LogMessage exits or crashes. - // By default this function does nothing. - // Using this function one can implement complex logic for send() - // that itself involves logging; and do all this w/o causing deadlocks and - // inconsistent rearrangement of log messages. - // E.g. if a LogSink has thread-specific actions, the send() method - // can simply add the message to a queue and wake up another thread that - // handles real logging while itself making some LOG() calls; - // WaitTillSent() can be implemented to wait for that logic to complete. - // See our unittest for an example. - virtual void WaitTillSent(); - - // Returns the normal text output of the log message. - // Can be useful to implement send(). - static std::string ToString(LogSeverity severity, const char* file, int line, - const struct ::tm* tm_time, - const char* message, size_t message_len); -}; - -// Add or remove a LogSink as a consumer of logging data. Thread-safe. -GOOGLE_GLOG_DLL_DECL void AddLogSink(LogSink *destination); -GOOGLE_GLOG_DLL_DECL void RemoveLogSink(LogSink *destination); - -// -// Specify an "extension" added to the filename specified via -// SetLogDestination. This applies to all severity levels. It's -// often used to append the port we're listening on to the logfile -// name. Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetLogFilenameExtension( - const char* filename_extension); - -// -// Make it so that all log messages of at least a particular severity -// are logged to stderr (in addition to logging to the usual log -// file(s)). Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetStderrLogging(LogSeverity min_severity); - -// -// Make it so that all log messages go only to stderr. Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void LogToStderr(); - -// -// Make it so that all log messages of at least a particular severity are -// logged via email to a list of addresses (in addition to logging to the -// usual log file(s)). The list of addresses is just a string containing -// the email addresses to send to (separated by spaces, say). Thread-safe. -// -GOOGLE_GLOG_DLL_DECL void SetEmailLogging(LogSeverity min_severity, - const char* addresses); - -// A simple function that sends email. dest is a commma-separated -// list of addressess. Thread-safe. -GOOGLE_GLOG_DLL_DECL bool SendEmail(const char *dest, - const char *subject, const char *body); - -GOOGLE_GLOG_DLL_DECL const std::vector& GetLoggingDirectories(); - -// For tests only: Clear the internal [cached] list of logging directories to -// force a refresh the next time GetLoggingDirectories is called. -// Thread-hostile. -void TestOnly_ClearLoggingDirectoriesList(); - -// Returns a set of existing temporary directories, which will be a -// subset of the directories returned by GetLogginDirectories(). -// Thread-safe. -GOOGLE_GLOG_DLL_DECL void GetExistingTempDirectories( - std::vector* list); - -// Print any fatal message again -- useful to call from signal handler -// so that the last thing in the output is the fatal message. -// Thread-hostile, but a race is unlikely. -GOOGLE_GLOG_DLL_DECL void ReprintFatalMessage(); - -// Truncate a log file that may be the append-only output of multiple -// processes and hence can't simply be renamed/reopened (typically a -// stdout/stderr). If the file "path" is > "limit" bytes, copy the -// last "keep" bytes to offset 0 and truncate the rest. Since we could -// be racing with other writers, this approach has the potential to -// lose very small amounts of data. For security, only follow symlinks -// if the path is /proc/self/fd/* -GOOGLE_GLOG_DLL_DECL void TruncateLogFile(const char *path, - int64 limit, int64 keep); - -// Truncate stdout and stderr if they are over the value specified by -// --max_log_size; keep the final 1MB. This function has the same -// race condition as TruncateLogFile. -GOOGLE_GLOG_DLL_DECL void TruncateStdoutStderr(); - -// Return the string representation of the provided LogSeverity level. -// Thread-safe. -GOOGLE_GLOG_DLL_DECL const char* GetLogSeverityName(LogSeverity severity); - -// --------------------------------------------------------------------- -// Implementation details that are not useful to most clients -// --------------------------------------------------------------------- - -// A Logger is the interface used by logging modules to emit entries -// to a log. A typical implementation will dump formatted data to a -// sequence of files. We also provide interfaces that will forward -// the data to another thread so that the invoker never blocks. -// Implementations should be thread-safe since the logging system -// will write to them from multiple threads. - -namespace base { - -class GOOGLE_GLOG_DLL_DECL Logger { - public: - virtual ~Logger(); - - // Writes "message[0,message_len-1]" corresponding to an event that - // occurred at "timestamp". If "force_flush" is true, the log file - // is flushed immediately. - // - // The input message has already been formatted as deemed - // appropriate by the higher level logging facility. For example, - // textual log messages already contain timestamps, and the - // file:linenumber header. - virtual void Write(bool force_flush, - time_t timestamp, - const char* message, - int message_len) = 0; - - // Flush any buffered messages - virtual void Flush() = 0; - - // Get the current LOG file size. - // The returned value is approximate since some - // logged data may not have been flushed to disk yet. - virtual uint32 LogSize() = 0; -}; - -// Get the logger for the specified severity level. The logger -// remains the property of the logging module and should not be -// deleted by the caller. Thread-safe. -extern GOOGLE_GLOG_DLL_DECL Logger* GetLogger(LogSeverity level); - -// Set the logger for the specified severity level. The logger -// becomes the property of the logging module and should not -// be deleted by the caller. Thread-safe. -extern GOOGLE_GLOG_DLL_DECL void SetLogger(LogSeverity level, Logger* logger); - -} - -// glibc has traditionally implemented two incompatible versions of -// strerror_r(). There is a poorly defined convention for picking the -// version that we want, but it is not clear whether it even works with -// all versions of glibc. -// So, instead, we provide this wrapper that automatically detects the -// version that is in use, and then implements POSIX semantics. -// N.B. In addition to what POSIX says, we also guarantee that "buf" will -// be set to an empty string, if this function failed. This means, in most -// cases, you do not need to check the error code and you can directly -// use the value of "buf". It will never have an undefined value. -// DEPRECATED: Use StrError(int) instead. -GOOGLE_GLOG_DLL_DECL int posix_strerror_r(int err, char *buf, size_t len); - -// A thread-safe replacement for strerror(). Returns a string describing the -// given POSIX error code. -GOOGLE_GLOG_DLL_DECL std::string StrError(int err); - -// A class for which we define operator<<, which does nothing. -class GOOGLE_GLOG_DLL_DECL NullStream : public LogMessage::LogStream { - public: - // Initialize the LogStream so the messages can be written somewhere - // (they'll never be actually displayed). This will be needed if a - // NullStream& is implicitly converted to LogStream&, in which case - // the overloaded NullStream::operator<< will not be invoked. - NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { } - NullStream(const char* /*file*/, int /*line*/, - const CheckOpString& /*result*/) : - LogMessage::LogStream(message_buffer_, 1, 0) { } - NullStream &stream() { return *this; } - private: - // A very short buffer for messages (which we discard anyway). This - // will be needed if NullStream& converted to LogStream& (e.g. as a - // result of a conditional expression). - char message_buffer_[2]; -}; - -// Do nothing. This operator is inline, allowing the message to be -// compiled away. The message will not be compiled away if we do -// something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when -// SKIP_LOG=WARNING. In those cases, NullStream will be implicitly -// converted to LogStream and the message will be computed and then -// quietly discarded. -template -inline NullStream& operator<<(NullStream &str, const T &) { return str; } - -// Similar to NullStream, but aborts the program (without stack -// trace), like LogMessageFatal. -class GOOGLE_GLOG_DLL_DECL NullStreamFatal : public NullStream { - public: - NullStreamFatal() { } - NullStreamFatal(const char* file, int line, const CheckOpString& result) : - NullStream(file, line, result) { } - __declspec(noreturn) ~NullStreamFatal() throw () { _exit(1); } -}; - -// Install a signal handler that will dump signal information and a stack -// trace when the program crashes on certain signals. We'll install the -// signal handler for the following signals. -// -// SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGBUS, and SIGTERM. -// -// By default, the signal handler will write the failure dump to the -// standard error. You can customize the destination by installing your -// own writer function by InstallFailureWriter() below. -// -// Note on threading: -// -// The function should be called before threads are created, if you want -// to use the failure signal handler for all threads. The stack trace -// will be shown only for the thread that receives the signal. In other -// words, stack traces of other threads won't be shown. -GOOGLE_GLOG_DLL_DECL void InstallFailureSignalHandler(); - -// Installs a function that is used for writing the failure dump. "data" -// is the pointer to the beginning of a message to be written, and "size" -// is the size of the message. You should not expect the data is -// terminated with '\0'. -GOOGLE_GLOG_DLL_DECL void InstallFailureWriter( - void (*writer)(const char* data, int size)); - -} - -#endif // _LOGGING_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/raw_logging.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/raw_logging.h deleted file mode 100755 index e0e6d6f1a25..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/raw_logging.h +++ /dev/null @@ -1,184 +0,0 @@ -// This file is automatically generated from src/glog/raw_logging.h.in -// using src/windows/preprocess.sh. -// DO NOT EDIT! - -// Copyright (c) 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Maxim Lifantsev -// -// Thread-safe logging routines that do not allocate any memory or -// acquire any locks, and can therefore be used by low-level memory -// allocation and synchronization code. - -#ifndef BASE_RAW_LOGGING_H_ -#define BASE_RAW_LOGGING_H_ - -#include - -namespace google { - -#include "glog/log_severity.h" -#include "glog/vlog_is_on.h" - -// Annoying stuff for windows -- makes sure clients can import these functions -#ifndef GOOGLE_GLOG_DLL_DECL -# if defined(_WIN32) && !defined(__CYGWIN__) -# define GOOGLE_GLOG_DLL_DECL __declspec(dllimport) -# else -# define GOOGLE_GLOG_DLL_DECL -# endif -#endif - -// This is similar to LOG(severity) << format... and VLOG(level) << format.., -// but -// * it is to be used ONLY by low-level modules that can't use normal LOG() -// * it is desiged to be a low-level logger that does not allocate any -// memory and does not need any locks, hence: -// * it logs straight and ONLY to STDERR w/o buffering -// * it uses an explicit format and arguments list -// * it will silently chop off really long message strings -// Usage example: -// RAW_LOG(ERROR, "Failed foo with %i: %s", status, error); -// RAW_VLOG(3, "status is %i", status); -// These will print an almost standard log lines like this to stderr only: -// E0821 211317 file.cc:123] RAW: Failed foo with 22: bad_file -// I0821 211317 file.cc:142] RAW: status is 20 -#define RAW_LOG(severity, ...) \ - do { \ - switch (google::GLOG_ ## severity) { \ - case 0: \ - RAW_LOG_INFO(__VA_ARGS__); \ - break; \ - case 1: \ - RAW_LOG_WARNING(__VA_ARGS__); \ - break; \ - case 2: \ - RAW_LOG_ERROR(__VA_ARGS__); \ - break; \ - case 3: \ - RAW_LOG_FATAL(__VA_ARGS__); \ - break; \ - default: \ - break; \ - } \ - } while (0) - -// The following STRIP_LOG testing is performed in the header file so that it's -// possible to completely compile out the logging code and the log messages. -#if STRIP_LOG == 0 -#define RAW_VLOG(verboselevel, ...) \ - do { \ - if (VLOG_IS_ON(verboselevel)) { \ - RAW_LOG_INFO(__VA_ARGS__); \ - } \ - } while (0) -#else -#define RAW_VLOG(verboselevel, ...) RawLogStub__(0, __VA_ARGS__) -#endif // STRIP_LOG == 0 - -#if STRIP_LOG == 0 -#define RAW_LOG_INFO(...) google::RawLog__(google::GLOG_INFO, \ - __FILE__, __LINE__, __VA_ARGS__) -#else -#define RAW_LOG_INFO(...) google::RawLogStub__(0, __VA_ARGS__) -#endif // STRIP_LOG == 0 - -#if STRIP_LOG <= 1 -#define RAW_LOG_WARNING(...) google::RawLog__(google::GLOG_WARNING, \ - __FILE__, __LINE__, __VA_ARGS__) -#else -#define RAW_LOG_WARNING(...) google::RawLogStub__(0, __VA_ARGS__) -#endif // STRIP_LOG <= 1 - -#if STRIP_LOG <= 2 -#define RAW_LOG_ERROR(...) google::RawLog__(google::GLOG_ERROR, \ - __FILE__, __LINE__, __VA_ARGS__) -#else -#define RAW_LOG_ERROR(...) google::RawLogStub__(0, __VA_ARGS__) -#endif // STRIP_LOG <= 2 - -#if STRIP_LOG <= 3 -#define RAW_LOG_FATAL(...) google::RawLog__(google::GLOG_FATAL, \ - __FILE__, __LINE__, __VA_ARGS__) -#else -#define RAW_LOG_FATAL(...) \ - do { \ - google::RawLogStub__(0, __VA_ARGS__); \ - exit(1); \ - } while (0) -#endif // STRIP_LOG <= 3 - -// Similar to CHECK(condition) << message, -// but for low-level modules: we use only RAW_LOG that does not allocate memory. -// We do not want to provide args list here to encourage this usage: -// if (!cond) RAW_LOG(FATAL, "foo ...", hard_to_compute_args); -// so that the args are not computed when not needed. -#define RAW_CHECK(condition, message) \ - do { \ - if (!(condition)) { \ - RAW_LOG(FATAL, "Check %s failed: %s", #condition, message); \ - } \ - } while (0) - -// Debug versions of RAW_LOG and RAW_CHECK -#ifndef NDEBUG - -#define RAW_DLOG(severity, ...) RAW_LOG(severity, __VA_ARGS__) -#define RAW_DCHECK(condition, message) RAW_CHECK(condition, message) - -#else // NDEBUG - -#define RAW_DLOG(severity, ...) \ - while (false) \ - RAW_LOG(severity, __VA_ARGS__) -#define RAW_DCHECK(condition, message) \ - while (false) \ - RAW_CHECK(condition, message) - -#endif // NDEBUG - -// Stub log function used to work around for unused variable warnings when -// building with STRIP_LOG > 0. -static inline void RawLogStub__(int /* ignored */, ...) { -} - -// Helper function to implement RAW_LOG and RAW_VLOG -// Logs format... at "severity" level, reporting it -// as called from file:line. -// This does not allocate memory or acquire locks. -GOOGLE_GLOG_DLL_DECL void RawLog__(LogSeverity severity, - const char* file, - int line, - const char* format, ...) - ; - -} - -#endif // BASE_RAW_LOGGING_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/stl_logging.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/stl_logging.h deleted file mode 100755 index a97a9089595..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/stl_logging.h +++ /dev/null @@ -1,224 +0,0 @@ -// This file is automatically generated from src/glog/stl_logging.h.in -// using src/windows/preprocess.sh. -// DO NOT EDIT! - -// Copyright (c) 2003, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Stream output operators for STL containers; to be used for logging *only*. -// Inclusion of this file lets you do: -// -// list x; -// LOG(INFO) << "data: " << x; -// vector v1, v2; -// CHECK_EQ(v1, v2); -// -// If you want to use this header file with hash_compare maps or slist, you -// need to define macros before including this file: -// -// - GLOG_STL_LOGGING_FOR_UNORDERED - and -// - GLOG_STL_LOGGING_FOR_TR1_UNORDERED - -// - GLOG_STL_LOGGING_FOR_EXT_HASH - -// - GLOG_STL_LOGGING_FOR_EXT_SLIST - -// - -#ifndef UTIL_GTL_STL_LOGGING_INL_H_ -#define UTIL_GTL_STL_LOGGING_INL_H_ - -#if !1 -# error We do not support stl_logging for this compiler -#endif - -#include -#include -#include -#include -#include -#include -#include - -#ifdef GLOG_STL_LOGGING_FOR_UNORDERED -# include -# include -#endif - -#ifdef GLOG_STL_LOGGING_FOR_TR1_UNORDERED -# include -# include -#endif - -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH -# include -# include -#endif -#ifdef GLOG_STL_LOGGING_FOR_EXT_SLIST -# include -#endif - -// Forward declare these two, and define them after all the container streams -// operators so that we can recurse from pair -> container -> container -> pair -// properly. -template -std::ostream& operator<<(std::ostream& out, const std::pair& p); - -namespace google { - -template -void PrintSequence(std::ostream& out, Iter begin, Iter end); - -} - -#define OUTPUT_TWO_ARG_CONTAINER(Sequence) \ -template \ -inline std::ostream& operator<<(std::ostream& out, \ - const Sequence& seq) { \ - google::PrintSequence(out, seq.begin(), seq.end()); \ - return out; \ -} - -OUTPUT_TWO_ARG_CONTAINER(std::vector) -OUTPUT_TWO_ARG_CONTAINER(std::deque) -OUTPUT_TWO_ARG_CONTAINER(std::list) -#ifdef GLOG_STL_LOGGING_FOR_EXT_SLIST -OUTPUT_TWO_ARG_CONTAINER(__gnu_cxx::slist) -#endif - -#undef OUTPUT_TWO_ARG_CONTAINER - -#define OUTPUT_THREE_ARG_CONTAINER(Sequence) \ -template \ -inline std::ostream& operator<<(std::ostream& out, \ - const Sequence& seq) { \ - google::PrintSequence(out, seq.begin(), seq.end()); \ - return out; \ -} - -OUTPUT_THREE_ARG_CONTAINER(std::set) -OUTPUT_THREE_ARG_CONTAINER(std::multiset) - -#undef OUTPUT_THREE_ARG_CONTAINER - -#define OUTPUT_FOUR_ARG_CONTAINER(Sequence) \ -template \ -inline std::ostream& operator<<(std::ostream& out, \ - const Sequence& seq) { \ - google::PrintSequence(out, seq.begin(), seq.end()); \ - return out; \ -} - -OUTPUT_FOUR_ARG_CONTAINER(std::map) -OUTPUT_FOUR_ARG_CONTAINER(std::multimap) -#ifdef GLOG_STL_LOGGING_FOR_UNORDERED -OUTPUT_FOUR_ARG_CONTAINER(std::unordered_set) -OUTPUT_FOUR_ARG_CONTAINER(std::unordered_multiset) -#endif -#ifdef GLOG_STL_LOGGING_FOR_TR1_UNORDERED -OUTPUT_FOUR_ARG_CONTAINER(std::tr1::unordered_set) -OUTPUT_FOUR_ARG_CONTAINER(std::tr1::unordered_multiset) -#endif -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH -OUTPUT_FOUR_ARG_CONTAINER(__gnu_cxx::hash_set) -OUTPUT_FOUR_ARG_CONTAINER(__gnu_cxx::hash_multiset) -#endif - -#undef OUTPUT_FOUR_ARG_CONTAINER - -#define OUTPUT_FIVE_ARG_CONTAINER(Sequence) \ -template \ -inline std::ostream& operator<<(std::ostream& out, \ - const Sequence& seq) { \ - google::PrintSequence(out, seq.begin(), seq.end()); \ - return out; \ -} - -#ifdef GLOG_STL_LOGGING_FOR_UNORDERED -OUTPUT_FIVE_ARG_CONTAINER(std::unordered_map) -OUTPUT_FIVE_ARG_CONTAINER(std::unordered_multimap) -#endif -#ifdef GLOG_STL_LOGGING_FOR_TR1_UNORDERED -OUTPUT_FIVE_ARG_CONTAINER(std::tr1::unordered_map) -OUTPUT_FIVE_ARG_CONTAINER(std::tr1::unordered_multimap) -#endif -#ifdef GLOG_STL_LOGGING_FOR_EXT_HASH -OUTPUT_FIVE_ARG_CONTAINER(__gnu_cxx::hash_map) -OUTPUT_FIVE_ARG_CONTAINER(__gnu_cxx::hash_multimap) -#endif - -#undef OUTPUT_FIVE_ARG_CONTAINER - -template -inline std::ostream& operator<<(std::ostream& out, - const std::pair& p) { - out << '(' << p.first << ", " << p.second << ')'; - return out; -} - -namespace google { - -template -inline void PrintSequence(std::ostream& out, Iter begin, Iter end) { - // Output at most 100 elements -- appropriate if used for logging. - for (int i = 0; begin != end && i < 100; ++i, ++begin) { - if (i > 0) out << ' '; - out << *begin; - } - if (begin != end) { - out << " ..."; - } -} - -} - -// Note that this is technically undefined behavior! We are adding things into -// the std namespace for a reason though -- we are providing new operations on -// types which are themselves defined with this namespace. Without this, these -// operator overloads cannot be found via ADL. If these definitions are not -// found via ADL, they must be #included before they're used, which requires -// this header to be included before apparently independent other headers. -// -// For example, base/logging.h defines various template functions to implement -// CHECK_EQ(x, y) and stream x and y into the log in the event the check fails. -// It does so via the function template MakeCheckOpValueString: -// template -// void MakeCheckOpValueString(strstream* ss, const T& v) { -// (*ss) << v; -// } -// Because 'glog/logging.h' is included before 'glog/stl_logging.h', -// subsequent CHECK_EQ(v1, v2) for vector<...> typed variable v1 and v2 can only -// find these operator definitions via ADL. -// -// Even this solution has problems -- it may pull unintended operators into the -// namespace as well, allowing them to also be found via ADL, and creating code -// that only works with a particular order of includes. Long term, we need to -// move all of the *definitions* into namespace std, bet we need to ensure no -// one references them first. This lets us take that step. We cannot define them -// in both because that would create ambiguous overloads when both are found. -namespace std { using ::operator<<; } - -#endif // UTIL_GTL_STL_LOGGING_INL_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/vlog_is_on.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/vlog_is_on.h deleted file mode 100755 index 409a4011b38..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/glog/vlog_is_on.h +++ /dev/null @@ -1,133 +0,0 @@ -// This file is automatically generated from src/glog/vlog_is_on.h.in -// using src/windows/preprocess.sh. -// DO NOT EDIT! - -// Copyright (c) 1999, 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Author: Ray Sidney and many others -// -// Defines the VLOG_IS_ON macro that controls the variable-verbosity -// conditional logging. -// -// It's used by VLOG and VLOG_IF in logging.h -// and by RAW_VLOG in raw_logging.h to trigger the logging. -// -// It can also be used directly e.g. like this: -// if (VLOG_IS_ON(2)) { -// // do some logging preparation and logging -// // that can't be accomplished e.g. via just VLOG(2) << ...; -// } -// -// The truth value that VLOG_IS_ON(level) returns is determined by -// the three verbosity level flags: -// --v= Gives the default maximal active V-logging level; -// 0 is the default. -// Normally positive values are used for V-logging levels. -// --vmodule= Gives the per-module maximal V-logging levels to override -// the value given by --v. -// E.g. "my_module=2,foo*=3" would change the logging level -// for all code in source files "my_module.*" and "foo*.*" -// ("-inl" suffixes are also disregarded for this matching). -// -// SetVLOGLevel helper function is provided to do limited dynamic control over -// V-logging by overriding the per-module settings given via --vmodule flag. -// -// CAVEAT: --vmodule functionality is not available in non gcc compilers. -// - -#ifndef BASE_VLOG_IS_ON_H_ -#define BASE_VLOG_IS_ON_H_ - -#include "glog/log_severity.h" - -// Annoying stuff for windows -- makes sure clients can import these functions -#ifndef GOOGLE_GLOG_DLL_DECL -# if defined(_WIN32) && !defined(__CYGWIN__) -# define GOOGLE_GLOG_DLL_DECL __declspec(dllimport) -# else -# define GOOGLE_GLOG_DLL_DECL -# endif -#endif - -#if defined(__GNUC__) -// We emit an anonymous static int* variable at every VLOG_IS_ON(n) site. -// (Normally) the first time every VLOG_IS_ON(n) site is hit, -// we determine what variable will dynamically control logging at this site: -// it's either FLAGS_v or an appropriate internal variable -// matching the current source file that represents results of -// parsing of --vmodule flag and/or SetVLOGLevel calls. -#define VLOG_IS_ON(verboselevel) \ - __extension__ \ - ({ static google::int32* vlocal__ = &google::kLogSiteUninitialized; \ - google::int32 verbose_level__ = (verboselevel); \ - (*vlocal__ >= verbose_level__) && \ - ((vlocal__ != &google::kLogSiteUninitialized) || \ - (google::InitVLOG3__(&vlocal__, &FLAGS_v, \ - __FILE__, verbose_level__))); }) -#else -// GNU extensions not available, so we do not support --vmodule. -// Dynamic value of FLAGS_v always controls the logging level. -#define VLOG_IS_ON(verboselevel) (FLAGS_v >= (verboselevel)) -#endif - -// Set VLOG(_IS_ON) level for module_pattern to log_level. -// This lets us dynamically control what is normally set by the --vmodule flag. -// Returns the level that previously applied to module_pattern. -// NOTE: To change the log level for VLOG(_IS_ON) sites -// that have already executed after/during InitGoogleLogging, -// one needs to supply the exact --vmodule pattern that applied to them. -// (If no --vmodule pattern applied to them -// the value of FLAGS_v will continue to control them.) -extern GOOGLE_GLOG_DLL_DECL int SetVLOGLevel(const char* module_pattern, - int log_level); - -// Various declarations needed for VLOG_IS_ON above: ========================= - -// Special value used to indicate that a VLOG_IS_ON site has not been -// initialized. We make this a large value, so the common-case check -// of "*vlocal__ >= verbose_level__" in VLOG_IS_ON definition -// passes in such cases and InitVLOG3__ is then triggered. -extern google::int32 kLogSiteUninitialized; - -// Helper routine which determines the logging info for a particalur VLOG site. -// site_flag is the address of the site-local pointer to the controlling -// verbosity level -// site_default is the default to use for *site_flag -// fname is the current source file name -// verbose_level is the argument to VLOG_IS_ON -// We will return the return value for VLOG_IS_ON -// and if possible set *site_flag appropriately. -extern GOOGLE_GLOG_DLL_DECL bool InitVLOG3__( - google::int32** site_flag, - google::int32* site_default, - const char* fname, - google::int32 verbose_level); - -#endif // BASE_VLOG_IS_ON_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/port.cc b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/port.cc deleted file mode 100755 index 19bda367c62..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/port.cc +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright (c) 2008, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --- - * Author: Craig Silverstein - * Copied from google-perftools and modified by Shinichiro Hamaji - */ - -#ifndef _WIN32 -# error You should only be including windows/port.cc in a windows environment! -#endif - -#include "config.h" -#include // for va_list, va_start, va_end -#include "port.h" - -// These call the windows _vsnprintf, but always NUL-terminate. -int safe_vsnprintf(char *str, size_t size, const char *format, va_list ap) { - if (size == 0) // not even room for a \0? - return -1; // not what C99 says to do, but what windows does - str[size-1] = '\0'; - return _vsnprintf(str, size-1, format, ap); -} - -#ifndef HAVE_LOCALTIME_R -struct tm* localtime_r(const time_t* timep, struct tm* result) { - localtime_s(result, timep); - return result; -} -#endif // not HAVE_LOCALTIME_R -#ifndef HAVE_SNPRINTF -int snprintf(char *str, size_t size, const char *format, ...) { - va_list ap; - va_start(ap, format); - const int r = vsnprintf(str, size, format, ap); - va_end(ap); - return r; -} -#endif diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/port.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/port.h deleted file mode 100755 index 7b4b9c8545b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/port.h +++ /dev/null @@ -1,174 +0,0 @@ -/* Copyright (c) 2008, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * --- - * Author: Craig Silverstein - * Copied from google-perftools and modified by Shinichiro Hamaji - * - * These are some portability typedefs and defines to make it a bit - * easier to compile this code under VC++. - * - * Several of these are taken from glib: - * http://developer.gnome.org/doc/API/glib/glib-windows-compatability-functions.html - */ - -#ifndef CTEMPLATE_WINDOWS_PORT_H_ -#define CTEMPLATE_WINDOWS_PORT_H_ - -#include "config.h" - -#ifdef _WIN32 - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN /* We always want minimal includes */ -#endif - -#include -#include /* for gethostname */ -#include /* because we so often use open/close/etc */ -#include /* for _getcwd() */ -#include /* for _getpid() */ -#include /* read in vsnprintf decl. before redifining it */ -#include /* template_dictionary.cc uses va_copy */ -#include /* for _strnicmp(), strerror_s() */ -#include /* for localtime_s() */ -/* Note: the C++ #includes are all together at the bottom. This file is - * used by both C and C++ code, so we put all the C++ together. - */ - -#ifdef _MSC_VER - -/* 4244: otherwise we get problems when substracting two size_t's to an int - * 4251: it's complaining about a private struct I've chosen not to dllexport - * 4355: we use this in a constructor, but we do it safely - * 4715: for some reason VC++ stopped realizing you can't return after abort() - * 4800: we know we're casting ints/char*'s to bools, and we're ok with that - * 4996: Yes, we're ok using "unsafe" functions like fopen() and strerror() - * 4312: Converting uint32_t to a pointer when testing %p - * 4267: also subtracting two size_t to int - * 4722: Destructor never returns due to abort() - */ -#pragma warning(disable:4244 4251 4355 4715 4800 4996 4267 4312 4722) - -/* file I/O */ -#define PATH_MAX 1024 -#define access _access -#define getcwd _getcwd -#define open _open -#define read _read -#define write _write -#define lseek _lseek -#define close _close -#define popen _popen -#define pclose _pclose -#define R_OK 04 /* read-only (for access()) */ -#define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR) - -#define O_WRONLY _O_WRONLY -#define O_CREAT _O_CREAT -#define O_EXCL _O_EXCL - -#ifndef __MINGW32__ -enum { STDIN_FILENO = 0, STDOUT_FILENO = 1, STDERR_FILENO = 2 }; -#endif -#define S_IRUSR S_IREAD -#define S_IWUSR S_IWRITE - -/* Not quite as lightweight as a hard-link, but more than good enough for us. */ -#define link(oldpath, newpath) CopyFileA(oldpath, newpath, false) - -#define strcasecmp _stricmp -#define strncasecmp _strnicmp - -/* In windows-land, hash<> is called hash_compare<> (from xhash.h) */ -/* VC11 provides std::hash */ -#if defined(_MSC_VER) && (_MSC_VER < 1700) -#define hash hash_compare -#endif - -/* Sleep is in ms, on windows */ -#define sleep(secs) Sleep((secs) * 1000) - -/* We can't just use _vsnprintf and _snprintf as drop-in-replacements, - * because they don't always NUL-terminate. :-( We also can't use the - * name vsnprintf, since windows defines that (but not snprintf (!)). - */ -#ifndef HAVE_SNPRINTF -extern int GOOGLE_GLOG_DLL_DECL snprintf(char *str, size_t size, - const char *format, ...); -#endif -extern int GOOGLE_GLOG_DLL_DECL safe_vsnprintf(char *str, size_t size, - const char *format, va_list ap); -#define vsnprintf(str, size, format, ap) safe_vsnprintf(str, size, format, ap) -#ifndef va_copy -#define va_copy(dst, src) (dst) = (src) -#endif - -/* Windows doesn't support specifying the number of buckets as a - * hash_map constructor arg, so we leave this blank. - */ -#define CTEMPLATE_SMALL_HASHTABLE - -#define DEFAULT_TEMPLATE_ROOTDIR ".." - -// ----------------------------------- SYSTEM/PROCESS -typedef int pid_t; -#define getpid _getpid - -#endif // _MSC_VER - -// ----------------------------------- THREADS -#if defined(HAVE_PTHREAD) -# include -#else // no PTHREAD -typedef DWORD pthread_t; -typedef DWORD pthread_key_t; -typedef LONG pthread_once_t; -enum { PTHREAD_ONCE_INIT = 0 }; // important that this be 0! for SpinLock -#define pthread_self GetCurrentThreadId -#define pthread_equal(pthread_t_1, pthread_t_2) ((pthread_t_1)==(pthread_t_2)) -#endif // HAVE_PTHREAD - -#ifndef HAVE_LOCALTIME_R -extern GOOGLE_GLOG_DLL_DECL struct tm* localtime_r(const time_t* timep, struct tm* result); -#endif // not HAVE_LOCALTIME_R - -inline char* strerror_r(int errnum, char* buf, size_t buflen) { - strerror_s(buf, buflen, errnum); - return buf; -} - -#ifndef __cplusplus -/* I don't see how to get inlining for C code in MSVC. Ah well. */ -#define inline -#endif - -#endif /* _WIN32 */ - -#endif /* CTEMPLATE_WINDOWS_PORT_H_ */ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/preprocess.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/preprocess.sh deleted file mode 100755 index c35e92913b6..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/src/windows/preprocess.sh +++ /dev/null @@ -1,119 +0,0 @@ -#!/bin/sh - -# Copyright (c) 2008, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# --- -# Author: Craig Silverstein -# Copied from google-perftools and modified by Shinichiro Hamaji -# -# This script is meant to be run at distribution-generation time, for -# instance by autogen.sh. It does some of the work configure would -# normally do, for windows systems. In particular, it expands all the -# @...@ variables found in .in files, and puts them here, in the windows -# directory. -# -# This script should be run before any new release. - -if [ -z "$1" ]; then - echo "USAGE: $0 " - exit 1 -fi - -DLLDEF_MACRO_NAME="GLOG_DLL_DECL" - -# The text we put in every .h files we create. As a courtesy, we'll -# include a helpful comment for windows users as to how to use -# GLOG_DLL_DECL. Apparently sed expands \n into a newline. Good! -DLLDEF_DEFINES="\ -// NOTE: if you are statically linking the template library into your binary\n\ -// (rather than using the template .dll), set '/D $DLLDEF_MACRO_NAME='\n\ -// as a compiler flag in your project file to turn off the dllimports.\n\ -#ifndef $DLLDEF_MACRO_NAME\n\ -# define $DLLDEF_MACRO_NAME __declspec(dllimport)\n\ -#endif" - -# Read all the windows config info into variables -# In order for the 'set' to take, this requires putting all in a subshell. -( - while read define varname value; do - [ "$define" != "#define" ] && continue - eval "$varname='$value'" - done - - # Process all the .in files in the "glog" subdirectory - mkdir -p "$1/windows/glog" - for file in `echo "$1"/glog/*.in`; do - echo "Processing $file" - outfile="$1/windows/glog/`basename $file .in`" - - echo "\ -// This file is automatically generated from $file -// using src/windows/preprocess.sh. -// DO NOT EDIT! -" > "$outfile" - # Besides replacing @...@, we also need to turn on dllimport - # We also need to replace hash by hash_compare (annoying we hard-code :-( ) - sed -e "s!@ac_windows_dllexport@!$DLLDEF_MACRO_NAME!g" \ - -e "s!@ac_windows_dllexport_defines@!$DLLDEF_DEFINES!g" \ - -e "s!@ac_cv_cxx_hash_map@!$HASH_MAP_H!g" \ - -e "s!@ac_cv_cxx_hash_namespace@!$HASH_NAMESPACE!g" \ - -e "s!@ac_cv_cxx_hash_set@!$HASH_SET_H!g" \ - -e "s!@ac_cv_have_stdint_h@!0!g" \ - -e "s!@ac_cv_have_systypes_h@!0!g" \ - -e "s!@ac_cv_have_inttypes_h@!0!g" \ - -e "s!@ac_cv_have_unistd_h@!0!g" \ - -e "s!@ac_cv_have_uint16_t@!0!g" \ - -e "s!@ac_cv_have_u_int16_t@!0!g" \ - -e "s!@ac_cv_have___uint16@!1!g" \ - -e "s!@ac_cv_have_libgflags@!0!g" \ - -e "s!@ac_cv_have___builtin_expect@!0!g" \ - -e "s!@ac_cv_cxx_using_operator@!1!g" \ - -e "s!@ac_cv___attribute___noreturn@!__declspec(noreturn)!g" \ - -e "s!@ac_cv___attribute___noinline@!!g" \ - -e "s!@ac_cv___attribute___printf_4_5@!!g" \ - -e "s!@ac_google_attribute@!${HAVE___ATTRIBUTE__:-0}!g" \ - -e "s!@ac_google_end_namespace@!$_END_GOOGLE_NAMESPACE_!g" \ - -e "s!@ac_google_namespace@!$GOOGLE_NAMESPACE!g" \ - -e "s!@ac_google_start_namespace@!$_START_GOOGLE_NAMESPACE_!g" \ - -e "s!@ac_htmlparser_namespace@!$HTMLPARSER_NAMESPACE!g" \ - -e "s!\\bhash\\b!hash_compare!g" \ - "$file" >> "$outfile" - done -) < "$1/windows/config.h" - -# log_severity.h isn't a .in file. -echo "\ -// This file is automatically generated from $1/glog/log_severity.h -// using src/windows/preprocess.sh. -// DO NOT EDIT! -" > "$1/windows/glog/log_severity.h" -cat "$1/glog/log_severity.h" >> "$1/windows/glog/log_severity.h" - -echo "DONE" diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/.gitignore b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/.gitignore deleted file mode 100644 index 13489ce3b5d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# allow toolchain files to be tracked by git -!*.cmake diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/clang-cxx17.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/clang-cxx17.cmake deleted file mode 100644 index 09d077a38d7..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/clang-cxx17.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Sample toolchain file for building with gcc compiler -# -# Typical usage: -# *) cmake -H. -B_build -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/gcc.cmake" - -# set compiler -set(CMAKE_C_COMPILER clang) -set(CMAKE_CXX_COMPILER clang++) - -# set c++ standard -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-cxx11.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-cxx11.cmake deleted file mode 100644 index da1ab5778a2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-cxx11.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Sample toolchain file for building with gcc compiler -# -# Typical usage: -# *) cmake -H. -B_build -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/gcc.cmake" - -# set compiler -set(CMAKE_C_COMPILER gcc) -set(CMAKE_CXX_COMPILER g++) - -# set c++ standard -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-cxx17.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-cxx17.cmake deleted file mode 100644 index 1b834f12015..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-cxx17.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Sample toolchain file for building with gcc compiler -# -# Typical usage: -# *) cmake -H. -B_build -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/gcc.cmake" - -# set compiler -set(CMAKE_C_COMPILER gcc) -set(CMAKE_CXX_COMPILER g++) - -# set c++ standard -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-cxx98.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-cxx98.cmake deleted file mode 100644 index 5697ab252aa..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-cxx98.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Sample toolchain file for building with gcc compiler -# -# Typical usage: -# *) cmake -H. -B_build -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/gcc.cmake" - -# set compiler -set(CMAKE_C_COMPILER gcc) -set(CMAKE_CXX_COMPILER g++) - -# set c++ standard -set(CMAKE_CXX_STANDARD 98) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-gnuxx11.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-gnuxx11.cmake deleted file mode 100644 index 91f0e4a3ce7..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/gcc-gnuxx11.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Sample toolchain file for building with gcc compiler -# -# Typical usage: -# *) cmake -H. -B_build -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/gcc.cmake" - -# set compiler -set(CMAKE_C_COMPILER gcc) -set(CMAKE_CXX_COMPILER g++) - -# set c++ standard -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS ON) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/linux-mingw-w64-cxx11.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/linux-mingw-w64-cxx11.cmake deleted file mode 100644 index 9c6e126a68d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/linux-mingw-w64-cxx11.cmake +++ /dev/null @@ -1,33 +0,0 @@ -# Sample toolchain file for building for Windows from an Ubuntu Linux system. -# -# Typical usage: -# *) install cross compiler: `sudo apt-get install mingw-w64` -# *) cmake -H. -B_build_mingw -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/linux-mingw-w64.cmake" - -set(CMAKE_SYSTEM_NAME Windows) -set(CMAKE_SYSTEM_PROCESSOR x86_64) -set(TOOLCHAIN_PREFIX x86_64-w64-mingw32) - -# set compiler -set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc) -set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++) -set(CMAKE_RC_COMPILER ${TOOLCHAIN_PREFIX}-windres) - -# target environment on the build host system -# set 1st to dir with the cross compiler's C/C++ headers/libs -set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX}) - -# modify default behavior of FIND_XXX() commands to -# search for headers/libs in the target environment and -# search for programs in the build host environment -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) - -# use emulator for `try_run` calls -set(CMAKE_CROSSCOMPILING_EMULATOR wine64) - -# set c++ standard -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/linux-mingw-w64-cxx17.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/linux-mingw-w64-cxx17.cmake deleted file mode 100644 index 1c363f10eb1..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/linux-mingw-w64-cxx17.cmake +++ /dev/null @@ -1,33 +0,0 @@ -# Sample toolchain file for building for Windows from an Ubuntu Linux system. -# -# Typical usage: -# *) install cross compiler: `sudo apt-get install mingw-w64` -# *) cmake -H. -B_build_mingw -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/linux-mingw-w64.cmake" - -set(CMAKE_SYSTEM_NAME Windows) -set(CMAKE_SYSTEM_PROCESSOR x86_64) -set(TOOLCHAIN_PREFIX x86_64-w64-mingw32) - -# set compiler -set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc) -set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++) -set(CMAKE_RC_COMPILER ${TOOLCHAIN_PREFIX}-windres) - -# target environment on the build host system -# set 1st to dir with the cross compiler's C/C++ headers/libs -set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX}) - -# modify default behavior of FIND_XXX() commands to -# search for headers/libs in the target environment and -# search for programs in the build host environment -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) - -# use emulator for `try_run` calls -set(CMAKE_CROSSCOMPILING_EMULATOR wine64) - -# set c++ standard -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/linux-mingw-w64-gnuxx11.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/linux-mingw-w64-gnuxx11.cmake deleted file mode 100644 index 99029649dfa..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/linux-mingw-w64-gnuxx11.cmake +++ /dev/null @@ -1,33 +0,0 @@ -# Sample toolchain file for building for Windows from an Ubuntu Linux system. -# -# Typical usage: -# *) install cross compiler: `sudo apt-get install mingw-w64` -# *) cmake -H. -B_build_mingw -DCMAKE_TOOLCHAIN_FILE="${PWD}/toolchains/linux-mingw-w64.cmake" - -set(CMAKE_SYSTEM_NAME Windows) -set(CMAKE_SYSTEM_PROCESSOR x86_64) -set(TOOLCHAIN_PREFIX x86_64-w64-mingw32) - -# set compiler -set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc) -set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++) -set(CMAKE_RC_COMPILER ${TOOLCHAIN_PREFIX}-windres) - -# target environment on the build host system -# set 1st to dir with the cross compiler's C/C++ headers/libs -set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX}) - -# modify default behavior of FIND_XXX() commands to -# search for headers/libs in the target environment and -# search for programs in the build host environment -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) - -# use emulator for `try_run` calls -set(CMAKE_CROSSCOMPILING_EMULATOR wine64) - -# set c++ standard -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS ON) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/mingw-cxx11.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/mingw-cxx11.cmake deleted file mode 100644 index 873f623f601..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/mingw-cxx11.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Sample toolchain file for building with gcc compiler -# -# Typical usage: -# *) cmake -H. -B_build -DCMAKE_TOOLCHAIN_FILE="%cd%\toolchains\mingw.cmake" - -# set compiler -set(CMAKE_C_COMPILER gcc) -set(CMAKE_CXX_COMPILER g++) - -# set c++ standard -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/mingw-cxx17.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/mingw-cxx17.cmake deleted file mode 100644 index c0c89cc459f..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/mingw-cxx17.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Sample toolchain file for building with gcc compiler -# -# Typical usage: -# *) cmake -H. -B_build -DCMAKE_TOOLCHAIN_FILE="%cd%\toolchains\mingw.cmake" - -# set compiler -set(CMAKE_C_COMPILER gcc) -set(CMAKE_CXX_COMPILER g++) - -# set c++ standard -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/mingw-gnuxx11.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/mingw-gnuxx11.cmake deleted file mode 100644 index 66337050c92..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/mingw-gnuxx11.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Sample toolchain file for building with gcc compiler -# -# Typical usage: -# *) cmake -H. -B_build -DCMAKE_TOOLCHAIN_FILE="%cd%\toolchains\mingw.cmake" - -# set compiler -set(CMAKE_C_COMPILER gcc) -set(CMAKE_CXX_COMPILER g++) - -# set c++ standard -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS YES) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-14-2015-sdk-8-1.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-14-2015-sdk-8-1.cmake deleted file mode 100644 index 463bee05238..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-14-2015-sdk-8-1.cmake +++ /dev/null @@ -1,2 +0,0 @@ -# set c++ standard -set(CMAKE_SYSTEM_VERSION 8.1) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-14-2015-win64.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-14-2015-win64.cmake deleted file mode 100644 index 00beda25efd..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-14-2015-win64.cmake +++ /dev/null @@ -1 +0,0 @@ -# dummy, nothing extra to set diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-15-2017-win64-cxx17.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-15-2017-win64-cxx17.cmake deleted file mode 100644 index 5e4e936872d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-15-2017-win64-cxx17.cmake +++ /dev/null @@ -1,2 +0,0 @@ -# set c++ standard -set(CMAKE_CXX_FLAGS_INIT "${CMAKE_CXX_FLAGS_INIT} /std:c++17") diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-15-2017-win64.cmake b/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-15-2017-win64.cmake deleted file mode 100644 index 00beda25efd..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/glog/toolchains/vs-15-2017-win64.cmake +++ /dev/null @@ -1 +0,0 @@ -# dummy, nothing extra to set diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/.clang-format b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/.clang-format deleted file mode 100644 index 5b9bfe6d224..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/.clang-format +++ /dev/null @@ -1,4 +0,0 @@ -# Run manually to reformat a file: -# clang-format -i --style=file -Language: Cpp -BasedOnStyle: Google diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/.gitignore b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/.gitignore deleted file mode 100644 index f08cb72a33c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/.gitignore +++ /dev/null @@ -1,84 +0,0 @@ -# Ignore CI build directory -build/ -xcuserdata -cmake-build-debug/ -.idea/ -bazel-bin -bazel-genfiles -bazel-googletest -bazel-out -bazel-testlogs -# python -*.pyc - -# Visual Studio files -.vs -*.sdf -*.opensdf -*.VC.opendb -*.suo -*.user -_ReSharper.Caches/ -Win32-Debug/ -Win32-Release/ -x64-Debug/ -x64-Release/ - -# Ignore autoconf / automake files -Makefile.in -aclocal.m4 -configure -build-aux/ -autom4te.cache/ -googletest/m4/libtool.m4 -googletest/m4/ltoptions.m4 -googletest/m4/ltsugar.m4 -googletest/m4/ltversion.m4 -googletest/m4/lt~obsolete.m4 -googlemock/m4 - -# Ignore generated directories. -googlemock/fused-src/ -googletest/fused-src/ - -# macOS files -.DS_Store -googletest/.DS_Store -googletest/xcode/.DS_Store - -# Ignore cmake generated directories and files. -CMakeFiles -CTestTestfile.cmake -Makefile -cmake_install.cmake -googlemock/CMakeFiles -googlemock/CTestTestfile.cmake -googlemock/Makefile -googlemock/cmake_install.cmake -googlemock/gtest -/bin -/googlemock/gmock.dir -/googlemock/gmock_main.dir -/googlemock/RUN_TESTS.vcxproj.filters -/googlemock/RUN_TESTS.vcxproj -/googlemock/INSTALL.vcxproj.filters -/googlemock/INSTALL.vcxproj -/googlemock/gmock_main.vcxproj.filters -/googlemock/gmock_main.vcxproj -/googlemock/gmock.vcxproj.filters -/googlemock/gmock.vcxproj -/googlemock/gmock.sln -/googlemock/ALL_BUILD.vcxproj.filters -/googlemock/ALL_BUILD.vcxproj -/lib -/Win32 -/ZERO_CHECK.vcxproj.filters -/ZERO_CHECK.vcxproj -/RUN_TESTS.vcxproj.filters -/RUN_TESTS.vcxproj -/INSTALL.vcxproj.filters -/INSTALL.vcxproj -/googletest-distribution.sln -/CMakeCache.txt -/ALL_BUILD.vcxproj.filters -/ALL_BUILD.vcxproj diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/.travis.yml b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/.travis.yml deleted file mode 100644 index 4b90bd06c83..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/.travis.yml +++ /dev/null @@ -1,85 +0,0 @@ -# Build matrix / environment variable are explained on: -# https://docs.travis-ci.com/user/customizing-the-build/ -# This file can be validated on: -# http://lint.travis-ci.org/ - -sudo: false -language: cpp - -# Define the matrix explicitly, manually expanding the combinations of (os, compiler, env). -# It is more tedious, but grants us far more flexibility. -matrix: - include: - - os: linux - dist: trusty - sudo: required - group: deprecated-2017Q3 - before_install: chmod -R +x ./ci/*platformio.sh - install: ./ci/install-platformio.sh - script: ./ci/build-platformio.sh - - os: linux - compiler: gcc - sudo : true - install: ./ci/install-linux.sh && ./ci/log-config.sh - script: ./ci/build-linux-bazel.sh - - os: linux - compiler: clang - sudo : true - install: ./ci/install-linux.sh && ./ci/log-config.sh - script: ./ci/build-linux-bazel.sh - - os: linux - group: deprecated-2017Q4 - compiler: gcc - install: ./ci/install-linux.sh && ./ci/log-config.sh - script: ./ci/build-linux-autotools.sh - env: VERBOSE=1 CXXFLAGS=-std=c++11 - - os: linux - group: deprecated-2017Q4 - compiler: gcc - env: BUILD_TYPE=Debug VERBOSE=1 CXX_FLAGS=-std=c++11 - - os: linux - group: deprecated-2017Q4 - compiler: clang - env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 -Wgnu-zero-variadic-macro-arguments - - os: linux - compiler: clang - env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 NO_EXCEPTION=ON NO_RTTI=ON COMPILER_IS_GNUCXX=ON - - os: osx - compiler: gcc - env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp - - os: osx - compiler: clang - env: BUILD_TYPE=Release VERBOSE=1 CXX_FLAGS=-std=c++11 HOMEBREW_LOGS=~/homebrew-logs HOMEBREW_TEMP=~/homebrew-temp - -# These are the install and build (script) phases for the most common entries in the matrix. They could be included -# in each entry in the matrix, but that is just repetitive. -install: - - ./ci/install-${TRAVIS_OS_NAME}.sh - - . ./ci/env-${TRAVIS_OS_NAME}.sh - - ./ci/log-config.sh - -script: ./ci/travis.sh - -# For sudo=false builds this section installs the necessary dependencies. -addons: - apt: - # List of whitelisted in travis packages for ubuntu-precise can be found here: - # https://github.com/travis-ci/apt-package-whitelist/blob/master/ubuntu-precise - # List of whitelisted in travis apt-sources: - # https://github.com/travis-ci/apt-source-whitelist/blob/master/ubuntu.json - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-precise-3.9 - packages: - - g++-4.9 - - clang-3.9 - update: true - homebrew: - packages: - - ccache - - gcc@4.9 - - llvm@3.9 - update: true - -notifications: - email: false diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/BUILD.bazel b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/BUILD.bazel deleted file mode 100644 index f0c4ce5451f..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/BUILD.bazel +++ /dev/null @@ -1,177 +0,0 @@ -# Copyright 2017 Google Inc. -# All Rights Reserved. -# -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# Bazel Build for Google C++ Testing Framework(Google Test) - -package(default_visibility = ["//visibility:public"]) - -licenses(["notice"]) - -config_setting( - name = "windows", - constraint_values = ["@bazel_tools//platforms:windows"], -) - -config_setting( - name = "has_absl", - values = {"define": "absl=1"}, -) - -# Library that defines the FRIEND_TEST macro. -cc_library( - name = "gtest_prod", - hdrs = ["googletest/include/gtest/gtest_prod.h"], - includes = ["googletest/include"], -) - -# Google Test including Google Mock -cc_library( - name = "gtest", - srcs = glob( - include = [ - "googletest/src/*.cc", - "googletest/src/*.h", - "googletest/include/gtest/**/*.h", - "googlemock/src/*.cc", - "googlemock/include/gmock/**/*.h", - ], - exclude = [ - "googletest/src/gtest-all.cc", - "googletest/src/gtest_main.cc", - "googlemock/src/gmock-all.cc", - "googlemock/src/gmock_main.cc", - ], - ), - hdrs = glob([ - "googletest/include/gtest/*.h", - "googlemock/include/gmock/*.h", - ]), - copts = select({ - ":windows": [], - "//conditions:default": ["-pthread"], - }), - defines = select({ - ":has_absl": ["GTEST_HAS_ABSL=1"], - "//conditions:default": [], - }), - includes = [ - "googlemock", - "googlemock/include", - "googletest", - "googletest/include", - ], - linkopts = select({ - ":windows": [], - "//conditions:default": ["-pthread"], - }), - deps = select({ - ":has_absl": [ - "@com_google_absl//absl/debugging:failure_signal_handler", - "@com_google_absl//absl/debugging:stacktrace", - "@com_google_absl//absl/debugging:symbolize", - "@com_google_absl//absl/strings", - "@com_google_absl//absl/types:optional", - "@com_google_absl//absl/types:variant", - ], - "//conditions:default": [], - }), - features = select({ - ":windows": ["windows_export_all_symbols"], - "//conditions:default": [], - }) -) - -cc_library( - name = "gtest_main", - srcs = ["googlemock/src/gmock_main.cc"], - deps = [":gtest"], - features = select({ - ":windows": ["windows_export_all_symbols"], - "//conditions:default": [], - }) -) - -# The following rules build samples of how to use gTest. -cc_library( - name = "gtest_sample_lib", - srcs = [ - "googletest/samples/sample1.cc", - "googletest/samples/sample2.cc", - "googletest/samples/sample4.cc", - ], - hdrs = [ - "googletest/samples/prime_tables.h", - "googletest/samples/sample1.h", - "googletest/samples/sample2.h", - "googletest/samples/sample3-inl.h", - "googletest/samples/sample4.h", - ], - features = select({ - ":windows": ["windows_export_all_symbols"], - "//conditions:default": [], - }) -) - -cc_test( - name = "gtest_samples", - size = "small", - # All Samples except: - # sample9 (main) - # sample10 (main and takes a command line option and needs to be separate) - srcs = [ - "googletest/samples/sample1_unittest.cc", - "googletest/samples/sample2_unittest.cc", - "googletest/samples/sample3_unittest.cc", - "googletest/samples/sample4_unittest.cc", - "googletest/samples/sample5_unittest.cc", - "googletest/samples/sample6_unittest.cc", - "googletest/samples/sample7_unittest.cc", - "googletest/samples/sample8_unittest.cc", - ], - deps = [ - "gtest_sample_lib", - ":gtest_main", - ], - linkstatic = 0, -) - -cc_test( - name = "sample9_unittest", - size = "small", - srcs = ["googletest/samples/sample9_unittest.cc"], - deps = [":gtest"], -) - -cc_test( - name = "sample10_unittest", - size = "small", - srcs = ["googletest/samples/sample10_unittest.cc"], - deps = [":gtest"], -) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/CMakeLists.txt b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/CMakeLists.txt deleted file mode 100644 index fa9d63ed61c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/CMakeLists.txt +++ /dev/null @@ -1,36 +0,0 @@ -# Note: CMake support is community-based. The maintainers do not use CMake -# internally. - -cmake_minimum_required(VERSION 2.8.8) - -project(googletest-distribution) -set(GOOGLETEST_VERSION 1.9.0) - -if (CMAKE_VERSION VERSION_LESS "3.1") - add_definitions(-std=c++11) -else() - set(CMAKE_CXX_STANDARD 11) - set(CMAKE_CXX_STANDARD_REQUIRED ON) - if(NOT CYGWIN) - set(CMAKE_CXX_EXTENSIONS OFF) - endif() -endif() - -if (POLICY CMP0048) - cmake_policy(SET CMP0048 NEW) -endif (POLICY CMP0048) - -enable_testing() - -include(CMakeDependentOption) -include(GNUInstallDirs) - -#Note that googlemock target already builds googletest -option(BUILD_GMOCK "Builds the googlemock subproject" ON) -option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON) - -if(BUILD_GMOCK) - add_subdirectory( googlemock ) -else() - add_subdirectory( googletest ) -endif() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/CONTRIBUTING.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/CONTRIBUTING.md deleted file mode 100644 index b52f8ee5fcc..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/CONTRIBUTING.md +++ /dev/null @@ -1,161 +0,0 @@ -# How to become a contributor and submit your own code - -## Contributor License Agreements - -We'd love to accept your patches! Before we can take them, we -have to jump a couple of legal hurdles. - -Please fill out either the individual or corporate Contributor License Agreement -(CLA). - - * If you are an individual writing original source code and you're sure you - own the intellectual property, then you'll need to sign an - [individual CLA](https://developers.google.com/open-source/cla/individual). - * If you work for a company that wants to allow you to contribute your work, - then you'll need to sign a - [corporate CLA](https://developers.google.com/open-source/cla/corporate). - -Follow either of the two links above to access the appropriate CLA and -instructions for how to sign and return it. Once we receive it, we'll be able to -accept your pull requests. - -## Are you a Googler? -If you are a Googler, you can either create an internal change or work on GitHub directly. - - -## Contributing A Patch - -1. Submit an issue describing your proposed change to the - [issue tracker](https://github.com/google/googletest). -1. Please don't mix more than one logical change per submittal, - because it makes the history hard to follow. If you want to make a - change that doesn't have a corresponding issue in the issue - tracker, please create one. -1. Also, coordinate with team members that are listed on the issue in - question. This ensures that work isn't being duplicated and - communicating your plan early also generally leads to better - patches. -1. If your proposed change is accepted, and you haven't already done so, sign a - Contributor License Agreement (see details above). -1. Fork the desired repo, develop and test your code changes. -1. Ensure that your code adheres to the existing style in the sample to which - you are contributing. -1. Ensure that your code has an appropriate set of unit tests which all pass. -1. Submit a pull request. - -## The Google Test and Google Mock Communities ## - -The Google Test community exists primarily through the -[discussion group](http://groups.google.com/group/googletestframework) -and the GitHub repository. -Likewise, the Google Mock community exists primarily through their own -[discussion group](http://groups.google.com/group/googlemock). -You are definitely encouraged to contribute to the -discussion and you can also help us to keep the effectiveness of the -group high by following and promoting the guidelines listed here. - -### Please Be Friendly ### - -Showing courtesy and respect to others is a vital part of the Google -culture, and we strongly encourage everyone participating in Google -Test development to join us in accepting nothing less. Of course, -being courteous is not the same as failing to constructively disagree -with each other, but it does mean that we should be respectful of each -other when enumerating the 42 technical reasons that a particular -proposal may not be the best choice. There's never a reason to be -antagonistic or dismissive toward anyone who is sincerely trying to -contribute to a discussion. - -Sure, C++ testing is serious business and all that, but it's also -a lot of fun. Let's keep it that way. Let's strive to be one of the -friendliest communities in all of open source. - -As always, discuss Google Test in the official GoogleTest discussion group. -You don't have to actually submit code in order to sign up. Your participation -itself is a valuable contribution. - -## Style - -To keep the source consistent, readable, diffable and easy to merge, -we use a fairly rigid coding style, as defined by the [google-styleguide](https://github.com/google/styleguide) project. All patches will be expected -to conform to the style outlined [here](https://google.github.io/styleguide/cppguide.html). -Use [.clang-format](https://github.com/google/googletest/blob/master/.clang-format) to check your formatting - -## Requirements for Contributors ### - -If you plan to contribute a patch, you need to build Google Test, -Google Mock, and their own tests from a git checkout, which has -further requirements: - - * [Python](https://www.python.org/) v2.3 or newer (for running some of - the tests and re-generating certain source files from templates) - * [CMake](https://cmake.org/) v2.6.4 or newer - * [GNU Build System](https://en.wikipedia.org/wiki/GNU_Build_System) - including automake (>= 1.9), autoconf (>= 2.59), and - libtool / libtoolize. - -## Developing Google Test ## - -This section discusses how to make your own changes to Google Test. - -### Testing Google Test Itself ### - -To make sure your changes work as intended and don't break existing -functionality, you'll want to compile and run Google Test's own tests. -For that you can use CMake: - - mkdir mybuild - cd mybuild - cmake -Dgtest_build_tests=ON ${GTEST_DIR} - -Make sure you have Python installed, as some of Google Test's tests -are written in Python. If the cmake command complains about not being -able to find Python (`Could NOT find PythonInterp (missing: -PYTHON_EXECUTABLE)`), try telling it explicitly where your Python -executable can be found: - - cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR} - -Next, you can build Google Test and all of its own tests. On \*nix, -this is usually done by 'make'. To run the tests, do - - make test - -All tests should pass. - -### Regenerating Source Files ## - -Some of Google Test's source files are generated from templates (not -in the C++ sense) using a script. -For example, the -file include/gtest/internal/gtest-type-util.h.pump is used to generate -gtest-type-util.h in the same directory. - -You don't need to worry about regenerating the source files -unless you need to modify them. You would then modify the -corresponding `.pump` files and run the '[pump.py](googletest/scripts/pump.py)' -generator script. See the [Pump Manual](googletest/docs/PumpManual.md). - -## Developing Google Mock ### - -This section discusses how to make your own changes to Google Mock. - -#### Testing Google Mock Itself #### - -To make sure your changes work as intended and don't break existing -functionality, you'll want to compile and run Google Test's own tests. -For that you'll need Autotools. First, make sure you have followed -the instructions above to configure Google Mock. -Then, create a build output directory and enter it. Next, - - ${GMOCK_DIR}/configure # try --help for more info - -Once you have successfully configured Google Mock, the build steps are -standard for GNU-style OSS packages. - - make # Standard makefile following GNU conventions - make check # Builds and runs all tests - all should pass. - -Note that when building your project against Google Mock, you are building -against Google Test as well. There is no need to configure Google Test -separately. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/LICENSE b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/LICENSE deleted file mode 100644 index 1941a11f8ce..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2008, Google Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/Makefile.am b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/Makefile.am deleted file mode 100644 index 7227e036908..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/Makefile.am +++ /dev/null @@ -1,16 +0,0 @@ -# Note: automake support is community-based. The maintainers do not use automake -# internally. - -## Process this file with automake to produce Makefile.in - -AUTOMAKE_OPTIONS = foreign - -# Build . before src so that our all-local and clean-local hooks kicks in at -# the right time. -SUBDIRS = googletest googlemock - -EXTRA_DIST = \ - BUILD.bazel \ - CMakeLists.txt \ - README.md \ - WORKSPACE diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/README.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/README.md deleted file mode 100644 index 37c21e1afc8..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/README.md +++ /dev/null @@ -1,129 +0,0 @@ - -# Google Test # - -[![Build Status](https://api.travis-ci.org/google/googletest.svg?branch=master)](https://travis-ci.org/google/googletest) -[![Build status](https://ci.appveyor.com/api/projects/status/4o38plt0xbo1ubc8/branch/master?svg=true)](https://ci.appveyor.com/project/GoogleTestAppVeyor/googletest/branch/master) - -**Future Plans**: -* 1.8.x Release - [the 1.8.x](https://github.com/google/googletest/releases/tag/release-1.8.1) is the last release that works with pre-C++11 compilers. The 1.8.x will not accept any requests for any new features and any bugfix requests will only be accepted if proven "critical" -* Post 1.8.x - work to improve/cleanup/pay technical debt. When this work is completed there will be a 1.9.x tagged release -* Post 1.9.x googletest will follow [Abseil Live at Head philosophy](https://abseil.io/about/philosophy) - - -Welcome to **Google Test**, Google's C++ test framework! - -This repository is a merger of the formerly separate GoogleTest and -GoogleMock projects. These were so closely related that it makes sense to -maintain and release them together. - -Please subscribe to the mailing list at googletestframework@googlegroups.com for questions, discussions, and development. -There is also an IRC channel on [OFTC](https://webchat.oftc.net/) (irc.oftc.net) #gtest available. - -Getting started information for **Google Test** is available in the -[Google Test Primer](googletest/docs/primer.md) documentation. - -**Google Mock** is an extension to Google Test for writing and using C++ mock -classes. See the separate [Google Mock documentation](googlemock/README.md). - -More detailed documentation for googletest (including build instructions) are -in its interior [googletest/README.md](googletest/README.md) file. - -## Features ## - - * An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework. - * Test discovery. - * A rich set of assertions. - * User-defined assertions. - * Death tests. - * Fatal and non-fatal failures. - * Value-parameterized tests. - * Type-parameterized tests. - * Various options for running the tests. - * XML test report generation. - -## Platforms ## - -Google test has been used on a variety of platforms: - - * Linux - * Mac OS X - * Windows - * Cygwin - * MinGW - * Windows Mobile - * Symbian - * PlatformIO - -## Who Is Using Google Test? ## - -In addition to many internal projects at Google, Google Test is also used by -the following notable projects: - - * The [Chromium projects](http://www.chromium.org/) (behind the Chrome - browser and Chrome OS). - * The [LLVM](http://llvm.org/) compiler. - * [Protocol Buffers](https://github.com/google/protobuf), Google's data - interchange format. - * The [OpenCV](http://opencv.org/) computer vision library. - * [tiny-dnn](https://github.com/tiny-dnn/tiny-dnn): header only, dependency-free deep learning framework in C++11. - -## Related Open Source Projects ## - -[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based automated test-runner and Graphical User Interface with powerful features for Windows and Linux platforms. - -[Google Test UI](https://github.com/ospector/gtest-gbar) is test runner that runs -your test binary, allows you to track its progress via a progress bar, and -displays a list of test failures. Clicking on one shows failure text. Google -Test UI is written in C#. - -[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event -listener for Google Test that implements the -[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test -result output. If your test runner understands TAP, you may find it useful. - -[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that -runs tests from your binary in parallel to provide significant speed-up. - -[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter) is a VS Code extension allowing to view Google Tests in a tree view, and run/debug your tests. - -## Requirements ## - -Google Test is designed to have fairly minimal requirements to build -and use with your projects, but there are some. Currently, we support -Linux, Windows, Mac OS X, and Cygwin. We will also make our best -effort to support other platforms (e.g. Solaris, AIX, and z/OS). -However, since core members of the Google Test project have no access -to these platforms, Google Test may have outstanding issues there. If -you notice any problems on your platform, please notify -[googletestframework@googlegroups.com](https://groups.google.com/forum/#!forum/googletestframework). Patches for fixing them are -even more welcome! - -### Linux Requirements ### - -These are the base requirements to build and use Google Test from a source -package (as described below): - - * GNU-compatible Make or gmake - * POSIX-standard shell - * POSIX(-2) Regular Expressions (regex.h) - * A C++11-standard-compliant compiler - -### Windows Requirements ### - - * Microsoft Visual C++ 2015 or newer - -### Cygwin Requirements ### - - * Cygwin v1.5.25-14 or newer - -### Mac OS X Requirements ### - - * Mac OS X v10.4 Tiger or newer - * Xcode Developer Tools - -## Contributing change - -Please read the [`CONTRIBUTING.md`](CONTRIBUTING.md) for details on -how to contribute to this project. - -Happy testing! diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/WORKSPACE b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/WORKSPACE deleted file mode 100644 index b69578bce64..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/WORKSPACE +++ /dev/null @@ -1,10 +0,0 @@ -workspace(name = "com_google_googletest") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -# Abseil -http_archive( - name = "com_google_absl", - urls = ["https://github.com/abseil/abseil-cpp/archive/master.zip"], - strip_prefix = "abseil-cpp-master", -) diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/appveyor.yml b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/appveyor.yml deleted file mode 100644 index 6ef08fd8df5..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/appveyor.yml +++ /dev/null @@ -1,154 +0,0 @@ -version: '{build}' - -os: Visual Studio 2015 - -environment: - matrix: - - compiler: msvc-15-seh - generator: "Visual Studio 15 2017" - build_system: cmake - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - - - compiler: msvc-15-seh - generator: "Visual Studio 15 2017 Win64" - build_system: cmake - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - enabled_on_pr: yes - - - compiler: msvc-15-seh - build_system: bazel - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - enabled_on_pr: yes - - - compiler: msvc-14-seh - build_system: cmake - generator: "Visual Studio 14 2015" - enabled_on_pr: yes - - - compiler: msvc-14-seh - build_system: cmake - generator: "Visual Studio 14 2015 Win64" - - - compiler: gcc-6.3.0-posix - build_system: cmake - generator: "MinGW Makefiles" - cxx_path: 'C:\mingw-w64\i686-6.3.0-posix-dwarf-rt_v5-rev1\mingw32\bin' - enabled_on_pr: yes - -configuration: - - Debug - -build: - verbosity: minimal - -install: -- ps: | - Write-Output "Compiler: $env:compiler" - Write-Output "Generator: $env:generator" - Write-Output "Env:Configuation: $env:configuration" - Write-Output "Env: $env" - if (-not (Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER)) { - Write-Output "This is *NOT* a pull request build" - } else { - Write-Output "This is a pull request build" - if (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes") { - Write-Output "PR builds are *NOT* explicitly enabled" - } - } - - # install Bazel - if ($env:build_system -eq "bazel") { - appveyor DownloadFile https://github.com/bazelbuild/bazel/releases/download/0.21.0/bazel-0.21.0-windows-x86_64.exe -FileName bazel.exe - } - - if ($env:build_system -eq "cmake") { - # git bash conflicts with MinGW makefiles - if ($env:generator -eq "MinGW Makefiles") { - $env:path = $env:path.replace("C:\Program Files\Git\usr\bin;", "") - if ($env:cxx_path -ne "") { - $env:path += ";$env:cxx_path" - } - } - } - -before_build: -- ps: | - $env:root=$env:APPVEYOR_BUILD_FOLDER - Write-Output "env:root: $env:root" - -build_script: -- ps: | - # Only enable some builds for pull requests, the AppVeyor queue is too long. - if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) { - return - } else { - # special case - build with Bazel - if ($env:build_system -eq "bazel") { - & $env:root\bazel.exe build -c opt //:gtest_samples - if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error - $host.SetShouldExit(0) - } else { # a real error - throw "Exec: $ErrorMessage" - } - return - } - } - # by default build with CMake - md _build -Force | Out-Null - cd _build - - $conf = if ($env:generator -eq "MinGW Makefiles") {"-DCMAKE_BUILD_TYPE=$env:configuration"} else {"-DCMAKE_CONFIGURATION_TYPES=Debug;Release"} - # Disable test for MinGW (gtest tests fail, gmock tests can not build) - $gtest_build_tests = if ($env:generator -eq "MinGW Makefiles") {"-Dgtest_build_tests=OFF"} else {"-Dgtest_build_tests=ON"} - $gmock_build_tests = if ($env:generator -eq "MinGW Makefiles") {"-Dgmock_build_tests=OFF"} else {"-Dgmock_build_tests=ON"} - & cmake -G "$env:generator" $conf -Dgtest_build_samples=ON $gtest_build_tests $gmock_build_tests .. - if ($LastExitCode -ne 0) { - throw "Exec: $ErrorMessage" - } - $cmake_parallel = if ($env:generator -eq "MinGW Makefiles") {"-j2"} else {"/m"} - & cmake --build . --config $env:configuration -- $cmake_parallel - if ($LastExitCode -ne 0) { - throw "Exec: $ErrorMessage" - } - - -skip_commits: - files: - - '**/*.md' - -test_script: -- ps: | - # Only enable some builds for pull requests, the AppVeyor queue is too long. - if ((Test-Path env:APPVEYOR_PULL_REQUEST_NUMBER) -And (-not (Test-Path env:enabled_on_pr) -or $env:enabled_on_pr -ne "yes")) { - return - } - if ($env:build_system -eq "bazel") { - # special case - testing with Bazel - & $env:root\bazel.exe test //:gtest_samples - if ($LastExitCode -eq 0) { # bazel writes to StdErr and PowerShell interprets it as an error - $host.SetShouldExit(0) - } else { # a real error - throw "Exec: $ErrorMessage" - } - } - if ($env:build_system -eq "cmake") { - # built with CMake - test with CTest - if ($env:generator -eq "MinGW Makefiles") { - return # No test available for MinGW - } - - & ctest -C $env:configuration --timeout 600 --output-on-failure - if ($LastExitCode -ne 0) { - throw "Exec: $ErrorMessage" - } - } - -artifacts: - - path: '_build/CMakeFiles/*.log' - name: logs - - path: '_build/Testing/**/*.xml' - name: test_results - - path: 'bazel-testlogs/**/test.log' - name: test_logs - - path: 'bazel-testlogs/**/test.xml' - name: test_results diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/build-linux-autotools.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/build-linux-autotools.sh deleted file mode 100755 index cc404e9b242..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/build-linux-autotools.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2017 Google Inc. -# All Rights Reserved. -# -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -set -e - -. ci/get-nprocessors.sh - -# Create the configuration script -autoreconf -i - -# Run in a subdirectory to keep the sources clean -mkdir build || true -cd build -../configure - -make -j ${NPROCESSORS:-2} diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/build-linux-bazel.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/build-linux-bazel.sh deleted file mode 100755 index 3f1c7849551..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/build-linux-bazel.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2017 Google Inc. -# All Rights Reserved. -# -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -set -e - -bazel build --curses=no //...:all -bazel test --curses=no //...:all -bazel test --curses=no //...:all --define absl=1 diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/build-platformio.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/build-platformio.sh deleted file mode 100644 index 1d7658d8738..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/build-platformio.sh +++ /dev/null @@ -1,2 +0,0 @@ -# run PlatformIO builds -platformio run diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/env-linux.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/env-linux.sh deleted file mode 100755 index 37800d6a355..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/env-linux.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2017 Google Inc. -# All Rights Reserved. -# -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# -# This file should be sourced, and not executed as a standalone script. -# - -# TODO() - we can check if this is being sourced using $BASH_VERSION and $BASH_SOURCE[0] != ${0}. - -if [ "${TRAVIS_OS_NAME}" = "linux" ]; then - if [ "$CXX" = "g++" ]; then export CXX="g++-4.9" CC="gcc-4.9"; fi - if [ "$CXX" = "clang++" ]; then export CXX="clang++-3.9" CC="clang-3.9"; fi -fi diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/env-osx.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/env-osx.sh deleted file mode 100755 index 9c421e14314..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/env-osx.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2017 Google Inc. -# All Rights Reserved. -# -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# -# This file should be sourced, and not executed as a standalone script. -# - -# TODO() - we can check if this is being sourced using $BASH_VERSION and $BASH_SOURCE[0] != ${0}. -# - -if [ "${TRAVIS_OS_NAME}" = "osx" ]; then - if [ "$CXX" = "clang++" ]; then - # $PATH needs to be adjusted because the llvm tap doesn't install the - # package to /usr/local/bin, etc, like the gcc tap does. - # See: https://github.com/Homebrew/legacy-homebrew/issues/29733 - clang_version=3.9 - export PATH="/usr/local/opt/llvm@${clang_version}/bin:$PATH"; - fi -fi diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/get-nprocessors.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/get-nprocessors.sh deleted file mode 100755 index 43635e761e2..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/get-nprocessors.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2017 Google Inc. -# All Rights Reserved. -# -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -# This file is typically sourced by another script. -# if possible, ask for the precise number of processors, -# otherwise take 2 processors as reasonable default; see -# https://docs.travis-ci.com/user/speeding-up-the-build/#Makefile-optimization -if [ -x /usr/bin/getconf ]; then - NPROCESSORS=$(/usr/bin/getconf _NPROCESSORS_ONLN) -else - NPROCESSORS=2 -fi - -# as of 2017-09-04 Travis CI reports 32 processors, but GCC build -# crashes if parallelized too much (maybe memory consumption problem), -# so limit to 4 processors for the time being. -if [ $NPROCESSORS -gt 4 ] ; then - echo "$0:Note: Limiting processors to use by make from $NPROCESSORS to 4." - NPROCESSORS=4 -fi diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/install-linux.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/install-linux.sh deleted file mode 100755 index 05e2cb28031..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/install-linux.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2017 Google Inc. -# All Rights Reserved. -# -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -set -eu - -if [ "${TRAVIS_OS_NAME}" != linux ]; then - echo "Not a Linux build; skipping installation" - exit 0 -fi - - -if [ "${TRAVIS_SUDO}" = "true" ]; then - echo "deb [arch=amd64] http://storage.googleapis.com/bazel-apt stable jdk1.8" | \ - sudo tee /etc/apt/sources.list.d/bazel.list - curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add - - sudo apt-get update && sudo apt-get install -y bazel gcc-4.9 g++-4.9 clang-3.9 -elif [ "${CXX}" = "clang++" ]; then - # Use ccache, assuming $HOME/bin is in the path, which is true in the Travis build environment. - ln -sf /usr/bin/ccache $HOME/bin/${CXX}; - ln -sf /usr/bin/ccache $HOME/bin/${CC}; -fi diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/install-osx.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/install-osx.sh deleted file mode 100755 index f2baebd2974..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/install-osx.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2017 Google Inc. -# All Rights Reserved. -# -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -set -eu - -if [ "${TRAVIS_OS_NAME}" != "osx" ]; then - echo "Not a macOS build; skipping installation" - exit 0 -fi - -brew update -brew install ccache gcc@4.9 llvm@3.9 diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/install-platformio.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/install-platformio.sh deleted file mode 100644 index 4d7860a560c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/install-platformio.sh +++ /dev/null @@ -1,5 +0,0 @@ -# install PlatformIO -sudo pip install -U platformio - -# update PlatformIO -platformio update diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/log-config.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/log-config.sh deleted file mode 100755 index 5fef11948b1..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/log-config.sh +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2017 Google Inc. -# All Rights Reserved. -# -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -set -e - -# ccache on OS X needs installation first -# reset ccache statistics -ccache --zero-stats - -echo PATH=${PATH} - -echo "Compiler configuration:" -echo CXX=${CXX} -echo CC=${CC} -echo CXXFLAGS=${CXXFLAGS} - -echo "C++ compiler version:" -${CXX} --version || echo "${CXX} does not seem to support the --version flag" -${CXX} -v || echo "${CXX} does not seem to support the -v flag" - -echo "C compiler version:" -${CC} --version || echo "${CXX} does not seem to support the --version flag" -${CC} -v || echo "${CXX} does not seem to support the -v flag" diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/travis.sh b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/travis.sh deleted file mode 100755 index 9ff3bad3eeb..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/ci/travis.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env sh -set -evx - -. ci/get-nprocessors.sh - -# if possible, ask for the precise number of processors, -# otherwise take 2 processors as reasonable default; see -# https://docs.travis-ci.com/user/speeding-up-the-build/#Makefile-optimization -if [ -x /usr/bin/getconf ]; then - NPROCESSORS=$(/usr/bin/getconf _NPROCESSORS_ONLN) -else - NPROCESSORS=2 -fi -# as of 2017-09-04 Travis CI reports 32 processors, but GCC build -# crashes if parallelized too much (maybe memory consumption problem), -# so limit to 4 processors for the time being. -if [ $NPROCESSORS -gt 4 ] ; then - echo "$0:Note: Limiting processors to use by make from $NPROCESSORS to 4." - NPROCESSORS=4 -fi -# Tell make to use the processors. No preceding '-' required. -MAKEFLAGS="j${NPROCESSORS}" -export MAKEFLAGS - -env | sort - -# Set default values to OFF for these variables if not specified. -: "${NO_EXCEPTION:=OFF}" -: "${NO_RTTI:=OFF}" -: "${COMPILER_IS_GNUCXX:=OFF}" - -mkdir build || true -cd build -cmake -Dgtest_build_samples=ON \ - -Dgtest_build_tests=ON \ - -Dgmock_build_tests=ON \ - -Dcxx_no_exception=$NO_EXCEPTION \ - -Dcxx_no_rtti=$NO_RTTI \ - -DCMAKE_COMPILER_IS_GNUCXX=$COMPILER_IS_GNUCXX \ - -DCMAKE_CXX_FLAGS=$CXX_FLAGS \ - -DCMAKE_BUILD_TYPE=$BUILD_TYPE \ - .. -make -CTEST_OUTPUT_ON_FAILURE=1 make test diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/configure.ac b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/configure.ac deleted file mode 100644 index b963e9f0d9b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/configure.ac +++ /dev/null @@ -1,19 +0,0 @@ -# Note: automake support is community-based. The maintainers do not use automake -# internally. - -AC_INIT([Google C++ Mocking and Testing Frameworks], - [1.9.0], - [googlemock@googlegroups.com], - [googletest]) - -# Provide various options to initialize the Autoconf and configure processes. -AC_PREREQ([2.59]) -AC_CONFIG_SRCDIR([./README.md]) -AC_CONFIG_AUX_DIR([build-aux]) -AC_CONFIG_FILES([Makefile]) -AC_CONFIG_SUBDIRS([googletest googlemock]) - -AM_INIT_AUTOMAKE - -# Output the generated files. No further autoconf macros may be used. -AC_OUTPUT diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/CMakeLists.txt b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/CMakeLists.txt deleted file mode 100644 index c204f2719e8..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/CMakeLists.txt +++ /dev/null @@ -1,228 +0,0 @@ -######################################################################## -# Note: CMake support is community-based. The maintainers do not use CMake -# internally. -# -# CMake build script for Google Mock. -# -# To run the tests for Google Mock itself on Linux, use 'make test' or -# ctest. You can select which tests to run using 'ctest -R regex'. -# For more options, run 'ctest --help'. - -option(gmock_build_tests "Build all of Google Mock's own tests." OFF) - -# A directory to find Google Test sources. -if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt") - set(gtest_dir gtest) -else() - set(gtest_dir ../googletest) -endif() - -# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build(). -include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL) - -if (COMMAND pre_project_set_up_hermetic_build) - # Google Test also calls hermetic setup functions from add_subdirectory, - # although its changes will not affect things at the current scope. - pre_project_set_up_hermetic_build() -endif() - -######################################################################## -# -# Project-wide settings - -# Name of the project. -# -# CMake files in this project can refer to the root source directory -# as ${gmock_SOURCE_DIR} and to the root binary directory as -# ${gmock_BINARY_DIR}. -# Language "C" is required for find_package(Threads). -if (CMAKE_VERSION VERSION_LESS 3.0) - project(gmock CXX C) -else() - cmake_policy(SET CMP0048 NEW) - project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C) -endif() -cmake_minimum_required(VERSION 2.6.4) - -if (COMMAND set_up_hermetic_build) - set_up_hermetic_build() -endif() - -# Instructs CMake to process Google Test's CMakeLists.txt and add its -# targets to the current scope. We are placing Google Test's binary -# directory in a subdirectory of our own as VC compilation may break -# if they are the same (the default). -add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}") - - -# These commands only run if this is the main project -if(CMAKE_PROJECT_NAME STREQUAL "gmock" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution") - # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to - # make it prominent in the GUI. - option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF) -else() - mark_as_advanced(gmock_build_tests) -endif() - -# Although Google Test's CMakeLists.txt calls this function, the -# changes there don't affect the current scope. Therefore we have to -# call it again here. -config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake - -# Adds Google Mock's and Google Test's header directories to the search path. -set(gmock_build_include_dirs - "${gmock_SOURCE_DIR}/include" - "${gmock_SOURCE_DIR}" - "${gtest_SOURCE_DIR}/include" - # This directory is needed to build directly from Google Test sources. - "${gtest_SOURCE_DIR}") -include_directories(${gmock_build_include_dirs}) - -######################################################################## -# -# Defines the gmock & gmock_main libraries. User tests should link -# with one of them. - -# Google Mock libraries. We build them using more strict warnings than what -# are used for other targets, to ensure that Google Mock can be compiled by -# a user aggressive about warnings. -if (MSVC) - cxx_library(gmock - "${cxx_strict}" - "${gtest_dir}/src/gtest-all.cc" - src/gmock-all.cc) - - cxx_library(gmock_main - "${cxx_strict}" - "${gtest_dir}/src/gtest-all.cc" - src/gmock-all.cc - src/gmock_main.cc) -else() - cxx_library(gmock "${cxx_strict}" src/gmock-all.cc) - target_link_libraries(gmock PUBLIC gtest) - cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc) - target_link_libraries(gmock_main PUBLIC gmock) -endif() -# If the CMake version supports it, attach header directory information -# to the targets for when we are part of a parent build (ie being pulled -# in via add_subdirectory() rather than being a standalone build). -if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") - target_include_directories(gmock SYSTEM INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") - target_include_directories(gmock_main SYSTEM INTERFACE - "$" - "$/${CMAKE_INSTALL_INCLUDEDIR}>") -endif() - -######################################################################## -# -# Install rules -install_project(gmock gmock_main) - -######################################################################## -# -# Google Mock's own tests. -# -# You can skip this section if you aren't interested in testing -# Google Mock itself. -# -# The tests are not built by default. To build them, set the -# gmock_build_tests option to ON. You can do it by running ccmake -# or specifying the -Dgmock_build_tests=ON flag when running cmake. - -if (gmock_build_tests) - # This must be set in the root directory for the tests to be run by - # 'make test' or ctest. - enable_testing() - - if (WIN32) - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/$/RunTest.ps1" - CONTENT -"$project_bin = \"${CMAKE_BINARY_DIR}/bin/$\" -$env:Path = \"$project_bin;$env:Path\" -& $args") - elseif (MINGW) - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/RunTest.ps1" - CONTENT -"$project_bin = (cygpath --windows ${CMAKE_BINARY_DIR}/bin) -$env:Path = \"$project_bin;$env:Path\" -& $args") - endif() - - ############################################################ - # C++ tests built with standard compiler flags. - - cxx_test(gmock-actions_test gmock_main) - cxx_test(gmock-cardinalities_test gmock_main) - cxx_test(gmock_ex_test gmock_main) - cxx_test(gmock-function-mocker_test gmock_main) - cxx_test(gmock-generated-actions_test gmock_main) - cxx_test(gmock-generated-function-mockers_test gmock_main) - cxx_test(gmock-generated-matchers_test gmock_main) - cxx_test(gmock-internal-utils_test gmock_main) - cxx_test(gmock-matchers_test gmock_main) - if (MINGW) - target_compile_options(gmock-matchers_test PRIVATE "-Wa,-mbig-obj") - endif() - cxx_test(gmock-more-actions_test gmock_main) - cxx_test(gmock-nice-strict_test gmock_main) - cxx_test(gmock-port_test gmock_main) - cxx_test(gmock-spec-builders_test gmock_main) - cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc) - cxx_test(gmock_test gmock_main) - - if (DEFINED GTEST_HAS_PTHREAD) - cxx_test(gmock_stress_test gmock) - endif() - - # gmock_all_test is commented to save time building and running tests. - # Uncomment if necessary. - # cxx_test(gmock_all_test gmock_main) - - ############################################################ - # C++ tests built with non-standard compiler flags. - - if (MSVC) - cxx_library(gmock_main_no_exception "${cxx_no_exception}" - "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) - - cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" - "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) - - else() - cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc) - target_link_libraries(gmock_main_no_exception PUBLIC gmock) - - cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc) - target_link_libraries(gmock_main_no_rtti PUBLIC gmock) - endif() - cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}" - gmock_main_no_exception test/gmock-more-actions_test.cc) - - cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}" - gmock_main_no_rtti test/gmock-spec-builders_test.cc) - - cxx_shared_library(shared_gmock_main "${cxx_default}" - "${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc) - - # Tests that a binary can be built with Google Mock as a shared library. On - # some system configurations, it may not possible to run the binary without - # knowing more details about the system configurations. We do not try to run - # this binary. To get a more robust shared library coverage, configure with - # -DBUILD_SHARED_LIBS=ON. - cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}" - shared_gmock_main test/gmock-spec-builders_test.cc) - set_target_properties(shared_gmock_test_ - PROPERTIES - COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1") - - ############################################################ - # Python tests. - - cxx_executable(gmock_leak_test_ test gmock_main) - py_test(gmock_leak_test) - - cxx_executable(gmock_output_test_ test gmock) - py_test(gmock_output_test) -endif() diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/CONTRIBUTORS b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/CONTRIBUTORS deleted file mode 100644 index 6e9ae362b60..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/CONTRIBUTORS +++ /dev/null @@ -1,40 +0,0 @@ -# This file contains a list of people who've made non-trivial -# contribution to the Google C++ Mocking Framework project. People -# who commit code to the project are encouraged to add their names -# here. Please keep the list sorted by first names. - -Benoit Sigoure -Bogdan Piloca -Chandler Carruth -Dave MacLachlan -David Anderson -Dean Sturtevant -Gene Volovich -Hal Burch -Jeffrey Yasskin -Jim Keller -Joe Walnes -Jon Wray -Keir Mierle -Keith Ray -Kostya Serebryany -Lev Makhlis -Manuel Klimek -Mario Tanev -Mark Paskin -Markus Heule -Matthew Simmons -Mike Bland -Neal Norwitz -Nermin Ozkiranartli -Owen Carlsen -Paneendra Ba -Paul Menage -Piotr Kaminski -Russ Rufer -Sverre Sundsdal -Takeshi Yoshino -Vadim Berman -Vlad Losev -Wolfgang Klier -Zhanyong Wan diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/LICENSE b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/LICENSE deleted file mode 100644 index 1941a11f8ce..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2008, Google Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/Makefile.am b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/Makefile.am deleted file mode 100644 index 0b6f710d847..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/Makefile.am +++ /dev/null @@ -1,221 +0,0 @@ -# Note: automake support is community-based. The maintainers do not use automake -# internally. - -# Automake file - -ACLOCAL_AMFLAGS = -I m4 - -# Nonstandard package files for distribution. -EXTRA_DIST = LICENSE - -# We may need to build our internally packaged gtest. If so, it will be -# included in the 'subdirs' variable. -SUBDIRS = $(subdirs) - -# This is generated by the configure script, so clean it for distribution. -DISTCLEANFILES = scripts/gmock-config - -# We define the global AM_CPPFLAGS as everything we compile includes from these -# directories. -AM_CPPFLAGS = $(GTEST_CPPFLAGS) -I$(srcdir)/include - -# Modifies compiler and linker flags for pthreads compatibility. -if HAVE_PTHREADS - AM_CXXFLAGS = @PTHREAD_CFLAGS@ -DGTEST_HAS_PTHREAD=1 - AM_LIBS = @PTHREAD_LIBS@ -endif - -# Build rules for libraries. -lib_LTLIBRARIES = lib/libgmock.la lib/libgmock_main.la - -lib_libgmock_la_SOURCES = src/gmock-all.cc - -pkginclude_HEADERS = \ - include/gmock/gmock-actions.h \ - include/gmock/gmock-cardinalities.h \ - include/gmock/gmock-function-mocker.h \ - include/gmock/gmock-generated-actions.h \ - include/gmock/gmock-generated-function-mockers.h \ - include/gmock/gmock-generated-matchers.h \ - include/gmock/gmock-matchers.h \ - include/gmock/gmock-more-actions.h \ - include/gmock/gmock-more-matchers.h \ - include/gmock/gmock-nice-strict.h \ - include/gmock/gmock-spec-builders.h \ - include/gmock/gmock.h - -pkginclude_internaldir = $(pkgincludedir)/internal -pkginclude_internal_HEADERS = \ - include/gmock/internal/gmock-internal-utils.h \ - include/gmock/internal/gmock-port.h \ - include/gmock/internal/gmock-pp.h \ - include/gmock/internal/custom/gmock-generated-actions.h \ - include/gmock/internal/custom/gmock-matchers.h \ - include/gmock/internal/custom/gmock-port.h - -lib_libgmock_main_la_SOURCES = src/gmock_main.cc -lib_libgmock_main_la_LIBADD = lib/libgmock.la - -# Build rules for tests. Automake's naming for some of these variables isn't -# terribly obvious, so this is a brief reference: -# -# TESTS -- Programs run automatically by "make check" -# check_PROGRAMS -- Programs built by "make check" but not necessarily run - -TESTS= -check_PROGRAMS= -AM_LDFLAGS = $(GTEST_LDFLAGS) - -# This exercises all major components of Google Mock. It also -# verifies that libgmock works. -TESTS += test/gmock-spec-builders_test -check_PROGRAMS += test/gmock-spec-builders_test -test_gmock_spec_builders_test_SOURCES = test/gmock-spec-builders_test.cc -test_gmock_spec_builders_test_LDADD = $(GTEST_LIBS) lib/libgmock.la - -# This tests using Google Mock in multiple translation units. It also -# verifies that libgmock_main and libgmock work. -TESTS += test/gmock_link_test -check_PROGRAMS += test/gmock_link_test -test_gmock_link_test_SOURCES = \ - test/gmock_link2_test.cc \ - test/gmock_link_test.cc \ - test/gmock_link_test.h -test_gmock_link_test_LDADD = $(GTEST_LIBS) lib/libgmock_main.la lib/libgmock.la - -if HAVE_PYTHON - # Tests that fused gmock files compile and work. - TESTS += test/gmock_fused_test - check_PROGRAMS += test/gmock_fused_test - test_gmock_fused_test_SOURCES = \ - fused-src/gmock-gtest-all.cc \ - fused-src/gmock/gmock.h \ - fused-src/gmock_main.cc \ - fused-src/gtest/gtest.h \ - test/gmock_test.cc - test_gmock_fused_test_CPPFLAGS = -I"$(srcdir)/fused-src" -endif - -# Google Mock source files that we don't compile directly. -GMOCK_SOURCE_INGLUDES = \ - src/gmock-cardinalities.cc \ - src/gmock-internal-utils.cc \ - src/gmock-matchers.cc \ - src/gmock-spec-builders.cc \ - src/gmock.cc - -EXTRA_DIST += $(GMOCK_SOURCE_INGLUDES) - -# C++ tests that we don't compile using autotools. -EXTRA_DIST += \ - test/gmock-actions_test.cc \ - test/gmock_all_test.cc \ - test/gmock-cardinalities_test.cc \ - test/gmock_ex_test.cc \ - test/gmock-generated-actions_test.cc \ - test/gmock-function-mocker_test.cc \ - test/gmock-generated-function-mockers_test.cc \ - test/gmock-generated-matchers_test.cc \ - test/gmock-internal-utils_test.cc \ - test/gmock-matchers_test.cc \ - test/gmock-more-actions_test.cc \ - test/gmock-nice-strict_test.cc \ - test/gmock-port_test.cc \ - test/gmock_stress_test.cc - -# Python tests, which we don't run using autotools. -EXTRA_DIST += \ - test/gmock_leak_test.py \ - test/gmock_leak_test_.cc \ - test/gmock_output_test.py \ - test/gmock_output_test_.cc \ - test/gmock_output_test_golden.txt \ - test/gmock_test_utils.py - -# Nonstandard package files for distribution. -EXTRA_DIST += \ - CONTRIBUTORS \ - make/Makefile - -# Pump scripts for generating Google Mock headers. -EXTRA_DIST += \ - include/gmock/gmock-generated-actions.h.pump \ - include/gmock/gmock-generated-function-mockers.h.pump \ - include/gmock/gmock-generated-matchers.h.pump \ - include/gmock/internal/custom/gmock-generated-actions.h.pump - -# Script for fusing Google Mock and Google Test source files. -EXTRA_DIST += scripts/fuse_gmock_files.py - -# The Google Mock Generator tool from the cppclean project. -EXTRA_DIST += \ - scripts/generator/LICENSE \ - scripts/generator/README \ - scripts/generator/README.cppclean \ - scripts/generator/cpp/__init__.py \ - scripts/generator/cpp/ast.py \ - scripts/generator/cpp/gmock_class.py \ - scripts/generator/cpp/keywords.py \ - scripts/generator/cpp/tokenize.py \ - scripts/generator/cpp/utils.py \ - scripts/generator/gmock_gen.py - -# CMake scripts. -EXTRA_DIST += \ - CMakeLists.txt - -# Microsoft Visual Studio 2005 projects. -EXTRA_DIST += \ - msvc/2005/gmock.sln \ - msvc/2005/gmock.vcproj \ - msvc/2005/gmock_config.vsprops \ - msvc/2005/gmock_main.vcproj \ - msvc/2005/gmock_test.vcproj - -# Microsoft Visual Studio 2010 projects. -EXTRA_DIST += \ - msvc/2010/gmock.sln \ - msvc/2010/gmock.vcxproj \ - msvc/2010/gmock_config.props \ - msvc/2010/gmock_main.vcxproj \ - msvc/2010/gmock_test.vcxproj - -if HAVE_PYTHON -# gmock_test.cc does not really depend on files generated by the -# fused-gmock-internal rule. However, gmock_test.o does, and it is -# important to include test/gmock_test.cc as part of this rule in order to -# prevent compiling gmock_test.o until all dependent files have been -# generated. -$(test_gmock_fused_test_SOURCES): fused-gmock-internal - -fused-gmock-internal: $(pkginclude_HEADERS) $(pkginclude_internal_HEADERS) \ - $(lib_libgmock_la_SOURCES) $(GMOCK_SOURCE_INGLUDES) \ - $(lib_libgmock_main_la_SOURCES) \ - scripts/fuse_gmock_files.py - mkdir -p "$(srcdir)/fused-src" - chmod -R u+w "$(srcdir)/fused-src" - rm -f "$(srcdir)/fused-src/gtest/gtest.h" - rm -f "$(srcdir)/fused-src/gmock/gmock.h" - rm -f "$(srcdir)/fused-src/gmock-gtest-all.cc" - "$(srcdir)/scripts/fuse_gmock_files.py" "$(srcdir)/fused-src" - cp -f "$(srcdir)/src/gmock_main.cc" "$(srcdir)/fused-src" - -maintainer-clean-local: - rm -rf "$(srcdir)/fused-src" -endif - -# Death tests may produce core dumps in the build directory. In case -# this happens, clean them to keep distcleancheck happy. -CLEANFILES = core - -# Disables 'make install' as installing a compiled version of Google -# Mock can lead to undefined behavior due to violation of the -# One-Definition Rule. - -install-exec-local: - echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Mock into your build system." - false - -install-data-local: - echo "'make install' is dangerous and not supported. Instead, see README for how to integrate Google Mock into your build system." - false diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/README.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/README.md deleted file mode 100644 index b18be27bd7b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/README.md +++ /dev/null @@ -1,293 +0,0 @@ -## Google Mock ## - -The Google C++ mocking framework. - -### Overview ### - -Google's framework for writing and using C++ mock classes. -It can help you derive better designs of your system and write better tests. - -It is inspired by: - - * [jMock](http://www.jmock.org/), - * [EasyMock](http://www.easymock.org/), and - * [Hamcrest](http://code.google.com/p/hamcrest/), - -and designed with C++'s specifics in mind. - -Google mock: - - * lets you create mock classes trivially using simple macros. - * supports a rich set of matchers and actions. - * handles unordered, partially ordered, or completely ordered expectations. - * is extensible by users. - -We hope you find it useful! - -### Features ### - - * Provides a declarative syntax for defining mocks. - * Can easily define partial (hybrid) mocks, which are a cross of real - and mock objects. - * Handles functions of arbitrary types and overloaded functions. - * Comes with a rich set of matchers for validating function arguments. - * Uses an intuitive syntax for controlling the behavior of a mock. - * Does automatic verification of expectations (no record-and-replay needed). - * Allows arbitrary (partial) ordering constraints on - function calls to be expressed,. - * Lets a user extend it by defining new matchers and actions. - * Does not use exceptions. - * Is easy to learn and use. - -Please see the project page above for more information as well as the -mailing list for questions, discussions, and development. There is -also an IRC channel on OFTC (irc.oftc.net) #gtest available. Please -join us! - -Please note that code under [scripts/generator](scripts/generator/) is -from [cppclean](http://code.google.com/p/cppclean/) and released under -the Apache License, which is different from Google Mock's license. - -## Getting Started ## - -If you are new to the project, we suggest that you read the user -documentation in the following order: - - * Learn the [basics](../googletest/docs/primer.md) of - Google Test, if you choose to use Google Mock with it (recommended). - * Read [Google Mock for Dummies](../googlemock/docs/ForDummies.md). - * Read the instructions below on how to build Google Mock. - -You can also watch Zhanyong's [talk](http://www.youtube.com/watch?v=sYpCyLI47rM) on Google Mock's usage and implementation. - -Once you understand the basics, check out the rest of the docs: - - * [CheatSheet](../googlemock/docs/CheatSheet.md) - all the commonly used stuff - at a glance. - * [CookBook](../googlemock/docs/CookBook.md) - recipes for getting things done, - including advanced techniques. - -If you need help, please check the -[KnownIssues](docs/KnownIssues.md) and -[FrequentlyAskedQuestions](docs/FrequentlyAskedQuestions.md) before -posting a question on the -[discussion group](http://groups.google.com/group/googlemock). - - -### Using Google Mock Without Google Test ### - -Google Mock is not a testing framework itself. Instead, it needs a -testing framework for writing tests. Google Mock works seamlessly -with [Google Test](https://github.com/google/googletest), but -you can also use it with [any C++ testing framework](../googlemock/docs/ForDummies.md#using-google-mock-with-any-testing-framework). - -### Requirements for End Users ### - -Google Mock is implemented on top of [Google Test]( -http://github.com/google/googletest/), and depends on it. -You must use the bundled version of Google Test when using Google Mock. - -You can also easily configure Google Mock to work with another testing -framework, although it will still need Google Test. Please read -["Using_Google_Mock_with_Any_Testing_Framework"]( - ../googlemock/docs/ForDummies.md#using-google-mock-with-any-testing-framework) -for instructions. - -Google Mock depends on advanced C++ features and thus requires a more -modern compiler. The following are needed to use Google Mock: - -#### Linux Requirements #### - - * GNU-compatible Make or "gmake" - * POSIX-standard shell - * POSIX(-2) Regular Expressions (regex.h) - * C++98-standard-compliant compiler (e.g. GCC 3.4 or newer) - -#### Windows Requirements #### - - * Microsoft Visual C++ 8.0 SP1 or newer - -#### Mac OS X Requirements #### - - * Mac OS X 10.4 Tiger or newer - * Developer Tools Installed - -### Requirements for Contributors ### - -We welcome patches. If you plan to contribute a patch, you need to -build Google Mock and its tests, which has further requirements: - - * Automake version 1.9 or newer - * Autoconf version 2.59 or newer - * Libtool / Libtoolize - * Python version 2.3 or newer (for running some of the tests and - re-generating certain source files from templates) - -### Building Google Mock ### - -#### Using CMake #### - -If you have CMake available, it is recommended that you follow the -[build instructions][gtest_cmakebuild] -as described for Google Test. - -If are using Google Mock with an -existing CMake project, the section -[Incorporating Into An Existing CMake Project][gtest_incorpcmake] -may be of particular interest. -To make it work for Google Mock you will need to change - - target_link_libraries(example gtest_main) - -to - - target_link_libraries(example gmock_main) - -This works because `gmock_main` library is compiled with Google Test. - -#### Preparing to Build (Unix only) #### - -If you are using a Unix system and plan to use the GNU Autotools build -system to build Google Mock (described below), you'll need to -configure it now. - -To prepare the Autotools build system: - - cd googlemock - autoreconf -fvi - -To build Google Mock and your tests that use it, you need to tell your -build system where to find its headers and source files. The exact -way to do it depends on which build system you use, and is usually -straightforward. - -This section shows how you can integrate Google Mock into your -existing build system. - -Suppose you put Google Mock in directory `${GMOCK_DIR}` and Google Test -in `${GTEST_DIR}` (the latter is `${GMOCK_DIR}/gtest` by default). To -build Google Mock, create a library build target (or a project as -called by Visual Studio and Xcode) to compile - - ${GTEST_DIR}/src/gtest-all.cc and ${GMOCK_DIR}/src/gmock-all.cc - -with - - ${GTEST_DIR}/include and ${GMOCK_DIR}/include - -in the system header search path, and - - ${GTEST_DIR} and ${GMOCK_DIR} - -in the normal header search path. Assuming a Linux-like system and gcc, -something like the following will do: - - g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ - -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \ - -pthread -c ${GTEST_DIR}/src/gtest-all.cc - g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ - -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \ - -pthread -c ${GMOCK_DIR}/src/gmock-all.cc - ar -rv libgmock.a gtest-all.o gmock-all.o - -(We need -pthread as Google Test and Google Mock use threads.) - -Next, you should compile your test source file with -${GTEST\_DIR}/include and ${GMOCK\_DIR}/include in the header search -path, and link it with gmock and any other necessary libraries: - - g++ -isystem ${GTEST_DIR}/include -isystem ${GMOCK_DIR}/include \ - -pthread path/to/your_test.cc libgmock.a -o your_test - -As an example, the make/ directory contains a Makefile that you can -use to build Google Mock on systems where GNU make is available -(e.g. Linux, Mac OS X, and Cygwin). It doesn't try to build Google -Mock's own tests. Instead, it just builds the Google Mock library and -a sample test. You can use it as a starting point for your own build -script. - -If the default settings are correct for your environment, the -following commands should succeed: - - cd ${GMOCK_DIR}/make - make - ./gmock_test - -If you see errors, try to tweak the contents of -[make/Makefile](make/Makefile) to make them go away. - -### Windows ### - -The msvc/2005 directory contains VC++ 2005 projects and the msvc/2010 -directory contains VC++ 2010 projects for building Google Mock and -selected tests. - -Change to the appropriate directory and run "msbuild gmock.sln" to -build the library and tests (or open the gmock.sln in the MSVC IDE). -If you want to create your own project to use with Google Mock, you'll -have to configure it to use the `gmock_config` propety sheet. For that: - - * Open the Property Manager window (View | Other Windows | Property Manager) - * Right-click on your project and select "Add Existing Property Sheet..." - * Navigate to `gmock_config.vsprops` or `gmock_config.props` and select it. - * In Project Properties | Configuration Properties | General | Additional - Include Directories, type /include. - -### Tweaking Google Mock ### - -Google Mock can be used in diverse environments. The default -configuration may not work (or may not work well) out of the box in -some environments. However, you can easily tweak Google Mock by -defining control macros on the compiler command line. Generally, -these macros are named like `GTEST_XYZ` and you define them to either 1 -or 0 to enable or disable a certain feature. - -We list the most frequently used macros below. For a complete list, -see file [${GTEST\_DIR}/include/gtest/internal/gtest-port.h]( -../googletest/include/gtest/internal/gtest-port.h). - -### As a Shared Library (DLL) ### - -Google Mock is compact, so most users can build and link it as a static -library for the simplicity. Google Mock can be used as a DLL, but the -same DLL must contain Google Test as well. See -[Google Test's README][gtest_readme] -for instructions on how to set up necessary compiler settings. - -### Tweaking Google Mock ### - -Most of Google Test's control macros apply to Google Mock as well. -Please see [Google Test's README][gtest_readme] for how to tweak them. - -### Upgrading from an Earlier Version ### - -We strive to keep Google Mock releases backward compatible. -Sometimes, though, we have to make some breaking changes for the -users' long-term benefits. This section describes what you'll need to -do if you are upgrading from an earlier version of Google Mock. - -#### Upgrading from 1.1.0 or Earlier #### - -You may need to explicitly enable or disable Google Test's own TR1 -tuple library. See the instructions in section "[Choosing a TR1 Tuple -Library](#choosing-a-tr1-tuple-library)". - -#### Upgrading from 1.4.0 or Earlier #### - -On platforms where the pthread library is available, Google Test and -Google Mock use it in order to be thread-safe. For this to work, you -may need to tweak your compiler and/or linker flags. Please see the -"[Multi-threaded Tests](../googletest/README.md#multi-threaded-tests)" section in file Google Test's README for what you may need to do. - -If you have custom matchers defined using `MatcherInterface` or -`MakePolymorphicMatcher()`, you'll need to update their definitions to -use the new matcher API ( -[monomorphic](./docs/CookBook.md#writing-new-monomorphic-matchers), -[polymorphic](./docs/CookBook.md#writing-new-polymorphic-matchers)). -Matchers defined using `MATCHER()` or `MATCHER_P*()` aren't affected. - -Happy testing! - -[gtest_readme]: ../googletest/README.md "googletest" -[gtest_cmakebuild]: ../googletest/README.md#using-cmake "Using CMake" -[gtest_incorpcmake]: ../googletest/README.md#incorporating-into-an-existing-cmake-project "Incorporating Into An Existing CMake Project" diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/cmake/gmock.pc.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/cmake/gmock.pc.in deleted file mode 100644 index 08e0454749b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/cmake/gmock.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ - -Name: gmock -Description: GoogleMock (without main() function) -Version: @PROJECT_VERSION@ -URL: https://github.com/google/googletest -Requires: gtest -Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@ -Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/cmake/gmock_main.pc.in b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/cmake/gmock_main.pc.in deleted file mode 100644 index b22fe614828..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/cmake/gmock_main.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=${pcfiledir}/../.. -libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@ - -Name: gmock_main -Description: GoogleMock (with main() function) -Version: @PROJECT_VERSION@ -URL: https://github.com/google/googletest -Requires: gmock -Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@ -Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@ @CMAKE_THREAD_LIBS_INIT@ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/configure.ac b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/configure.ac deleted file mode 100644 index 98de70253b5..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/configure.ac +++ /dev/null @@ -1,137 +0,0 @@ -# Note: automake support is community-based. The maintainers do not use automake -# internally. - -m4_include(../googletest/m4/acx_pthread.m4) - -AC_INIT([Google C++ Mocking Framework], - [1.8.0], - [googlemock@googlegroups.com], - [gmock]) - -# Provide various options to initialize the Autoconf and configure processes. -AC_PREREQ([2.59]) -AC_CONFIG_SRCDIR([./LICENSE]) -AC_CONFIG_MACRO_DIRS([m4]) -AC_CONFIG_AUX_DIR([build-aux]) -AC_CONFIG_HEADERS([build-aux/config.h]) -AC_CONFIG_FILES([Makefile]) -AC_CONFIG_FILES([scripts/gmock-config], [chmod +x scripts/gmock-config]) - -# Initialize Automake with various options. We require at least v1.9, prevent -# pedantic complaints about package files, and enable various distribution -# targets. -AM_INIT_AUTOMAKE([1.9 dist-bzip2 dist-zip foreign subdir-objects]) - -# Check for programs used in building Google Test. -AC_PROG_CC -AC_PROG_CXX -AC_LANG([C++]) -AC_PROG_LIBTOOL - -PYTHON= # We *do not* allow the user to specify a python interpreter -AC_PATH_PROG([PYTHON],[python],[:]) -AS_IF([test "$PYTHON" != ":"], - [AM_PYTHON_CHECK_VERSION([$PYTHON],[2.3],[:],[PYTHON=":"])]) -AM_CONDITIONAL([HAVE_PYTHON],[test "$PYTHON" != ":"]) - -# Configure pthreads. -AC_ARG_WITH([pthreads], - [AS_HELP_STRING([--with-pthreads], - [use pthreads (default is yes)])], - [with_pthreads=$withval], - [with_pthreads=check]) - -have_pthreads=no -AS_IF([test "x$with_pthreads" != "xno"], - [ACX_PTHREAD( - [], - [AS_IF([test "x$with_pthreads" != "xcheck"], - [AC_MSG_FAILURE( - [--with-pthreads was specified, but unable to be used])])]) - have_pthreads="$acx_pthread_ok"]) -AM_CONDITIONAL([HAVE_PTHREADS],[test "x$have_pthreads" == "xyes"]) -AC_SUBST(PTHREAD_CFLAGS) -AC_SUBST(PTHREAD_LIBS) - -# GoogleMock currently has hard dependencies upon GoogleTest above and beyond -# running its own test suite, so we both provide our own version in -# a subdirectory and provide some logic to use a custom version or a system -# installed version. -AC_ARG_WITH([gtest], - [AS_HELP_STRING([--with-gtest], - [Specifies how to find the gtest package. If no - arguments are given, the default behavior, a - system installed gtest will be used if present, - and an internal version built otherwise. If a - path is provided, the gtest built or installed at - that prefix will be used.])], - [], - [with_gtest=yes]) -AC_ARG_ENABLE([external-gtest], - [AS_HELP_STRING([--disable-external-gtest], - [Disables any detection or use of a system - installed or user provided gtest. Any option to - '--with-gtest' is ignored. (Default is enabled.)]) - ], [], [enable_external_gtest=yes]) -AS_IF([test "x$with_gtest" == "xno"], - [AC_MSG_ERROR([dnl -Support for GoogleTest was explicitly disabled. Currently GoogleMock has a hard -dependency upon GoogleTest to build, please provide a version, or allow -GoogleMock to use any installed version and fall back upon its internal -version.])]) - -# Setup various GTEST variables. -AC_ARG_VAR([GTEST_CONFIG], - [The exact path of Google Test's 'gtest-config' script.]) -AC_ARG_VAR([GTEST_CPPFLAGS], - [C-like preprocessor flags for Google Test.]) -AC_ARG_VAR([GTEST_CXXFLAGS], - [C++ compile flags for Google Test.]) -AC_ARG_VAR([GTEST_LDFLAGS], - [Linker path and option flags for Google Test.]) -AC_ARG_VAR([GTEST_LIBS], - [Library linking flags for Google Test.]) -AC_ARG_VAR([GTEST_VERSION], - [The version of Google Test available.]) -HAVE_BUILT_GTEST="no" - -GTEST_MIN_VERSION="1.8.0" - -AS_IF([test "x${enable_external_gtest}" = "xyes"], - [# Begin filling in variables as we are able. - AS_IF([test "x${with_gtest}" != "xyes"], - [AS_IF([test -x "${with_gtest}/scripts/gtest-config"], - [GTEST_CONFIG="${with_gtest}/scripts/gtest-config"], - [GTEST_CONFIG="${with_gtest}/bin/gtest-config"]) - AS_IF([test -x "${GTEST_CONFIG}"], [], - [AC_MSG_ERROR([dnl -Unable to locate either a built or installed Google Test at '${with_gtest}'.]) - ])]) - - AS_IF([test -x "${GTEST_CONFIG}"], [], - [AC_PATH_PROG([GTEST_CONFIG], [gtest-config])]) - AS_IF([test -x "${GTEST_CONFIG}"], - [AC_MSG_CHECKING([for Google Test version >= ${GTEST_MIN_VERSION}]) - AS_IF([${GTEST_CONFIG} --min-version=${GTEST_MIN_VERSION}], - [AC_MSG_RESULT([yes]) - HAVE_BUILT_GTEST="yes"], - [AC_MSG_RESULT([no])])])]) - -AS_IF([test "x${HAVE_BUILT_GTEST}" = "xyes"], - [GTEST_CPPFLAGS=`${GTEST_CONFIG} --cppflags` - GTEST_CXXFLAGS=`${GTEST_CONFIG} --cxxflags` - GTEST_LDFLAGS=`${GTEST_CONFIG} --ldflags` - GTEST_LIBS=`${GTEST_CONFIG} --libs` - GTEST_VERSION=`${GTEST_CONFIG} --version`], - [ - # GTEST_CONFIG needs to be executable both in a Makefile environment and - # in a shell script environment, so resolve an absolute path for it here. - GTEST_CONFIG="`pwd -P`/../googletest/scripts/gtest-config" - GTEST_CPPFLAGS='-I$(top_srcdir)/../googletest/include' - GTEST_CXXFLAGS='-g' - GTEST_LDFLAGS='' - GTEST_LIBS='$(top_builddir)/../googletest/lib/libgtest.la' - GTEST_VERSION="${GTEST_MIN_VERSION}"]) - -# Output the generated files. No further autoconf macros may be used. -AC_OUTPUT diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/CheatSheet.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/CheatSheet.md deleted file mode 100644 index bc2af11fb67..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/CheatSheet.md +++ /dev/null @@ -1,589 +0,0 @@ - - -# Defining a Mock Class # - -## Mocking a Normal Class ## - -Given -```cpp -class Foo { - ... - virtual ~Foo(); - virtual int GetSize() const = 0; - virtual string Describe(const char* name) = 0; - virtual string Describe(int type) = 0; - virtual bool Process(Bar elem, int count) = 0; -}; -``` -(note that `~Foo()` **must** be virtual) we can define its mock as -```cpp -#include "gmock/gmock.h" - -class MockFoo : public Foo { - MOCK_CONST_METHOD0(GetSize, int()); - MOCK_METHOD1(Describe, string(const char* name)); - MOCK_METHOD1(Describe, string(int type)); - MOCK_METHOD2(Process, bool(Bar elem, int count)); -}; -``` - -To create a "nice" mock object which ignores all uninteresting calls, -or a "strict" mock object, which treats them as failures: -```cpp -NiceMock nice_foo; // The type is a subclass of MockFoo. -StrictMock strict_foo; // The type is a subclass of MockFoo. -``` - -## Mocking a Class Template ## - -To mock -```cpp -template -class StackInterface { - public: - ... - virtual ~StackInterface(); - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; -``` -(note that `~StackInterface()` **must** be virtual) just append `_T` to the `MOCK_*` macros: -```cpp -template -class MockStack : public StackInterface { - public: - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Specifying Calling Conventions for Mock Functions ## - -If your mock function doesn't use the default calling convention, you -can specify it by appending `_WITH_CALLTYPE` to any of the macros -described in the previous two sections and supplying the calling -convention as the first argument to the macro. For example, -```cpp - MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); - MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); -``` -where `STDMETHODCALLTYPE` is defined by `` on Windows. - -# Using Mocks in Tests # - -The typical flow is: - 1. Import the Google Mock names you need to use. All Google Mock names are in the `testing` namespace unless they are macros or otherwise noted. - 1. Create the mock objects. - 1. Optionally, set the default actions of the mock objects. - 1. Set your expectations on the mock objects (How will they be called? What wil they do?). - 1. Exercise code that uses the mock objects; if necessary, check the result using [Google Test](../../googletest/) assertions. - 1. When a mock objects is destructed, Google Mock automatically verifies that all expectations on it have been satisfied. - -Here is an example: -```cpp -using ::testing::Return; // #1 - -TEST(BarTest, DoesThis) { - MockFoo foo; // #2 - - ON_CALL(foo, GetSize()) // #3 - .WillByDefault(Return(1)); - // ... other default actions ... - - EXPECT_CALL(foo, Describe(5)) // #4 - .Times(3) - .WillRepeatedly(Return("Category 5")); - // ... other expectations ... - - EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 -} // #6 -``` - -# Setting Default Actions # - -Google Mock has a **built-in default action** for any function that -returns `void`, `bool`, a numeric value, or a pointer. - -To customize the default action for functions with return type `T` globally: -```cpp -using ::testing::DefaultValue; - -// Sets the default value to be returned. T must be CopyConstructible. -DefaultValue::Set(value); -// Sets a factory. Will be invoked on demand. T must be MoveConstructible. -// T MakeT(); -DefaultValue::SetFactory(&MakeT); -// ... use the mocks ... -// Resets the default value. -DefaultValue::Clear(); -``` - -To customize the default action for a particular method, use `ON_CALL()`: -```cpp -ON_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .WillByDefault(action); -``` - -# Setting Expectations # - -`EXPECT_CALL()` sets **expectations** on a mock method (How will it be -called? What will it do?): -```cpp -EXPECT_CALL(mock_object, method(matchers)) - .With(multi_argument_matcher) ? - .Times(cardinality) ? - .InSequence(sequences) * - .After(expectations) * - .WillOnce(action) * - .WillRepeatedly(action) ? - .RetiresOnSaturation(); ? -``` - -If `Times()` is omitted, the cardinality is assumed to be: - - * `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; - * `Times(n)` when there are `n WillOnce()`s but no `WillRepeatedly()`, where `n` >= 1; or - * `Times(AtLeast(n))` when there are `n WillOnce()`s and a `WillRepeatedly()`, where `n` >= 0. - -A method with no `EXPECT_CALL()` is free to be invoked _any number of times_, and the default action will be taken each time. - -# Matchers # - -A **matcher** matches a _single_ argument. You can use it inside -`ON_CALL()` or `EXPECT_CALL()`, or use it to validate a value -directly: - -| Matcher | Description | -|:--------|:------------| -| `EXPECT_THAT(value, matcher)` | Asserts that `value` matches `matcher`. | -| `ASSERT_THAT(value, matcher)` | The same as `EXPECT_THAT(value, matcher)`, except that it generates a **fatal** failure. | - -Built-in matchers (where `argument` is the function argument) are -divided into several categories: - -## Wildcard ## -| Matcher | Description | -|:--------|:------------| -|`_`|`argument` can be any value of the correct type.| -|`A()` or `An()`|`argument` can be any value of type `type`. | - -## Generic Comparison ## - -| Matcher | Description | -|:---------------------|:------------------| -|`Eq(value)` or `value`|`argument == value`| -|`Ge(value)` |`argument >= value`| -|`Gt(value)` |`argument > value` | -|`Le(value)` |`argument <= value`| -|`Lt(value)` |`argument < value` | -|`Ne(value)` |`argument != value`| -|`IsNull()` |`argument` is a `NULL` pointer (raw or smart).| -|`NotNull()` |`argument` is a non-null pointer (raw or smart).| -|`Optional(m)` |`argument` is `optional<>` that contains a value matching `m`.| -|`VariantWith(m)` |`argument` is `variant<>` that holds the alternative of type T with a value matching `m`.| -|`Ref(variable)` |`argument` is a reference to `variable`.| -|`TypedEq(value)`|`argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded.| - -Except `Ref()`, these matchers make a _copy_ of `value` in case it's -modified or destructed later. If the compiler complains that `value` -doesn't have a public copy constructor, try wrap it in `ByRef()`, -e.g. `Eq(ByRef(non_copyable_value))`. If you do that, make sure -`non_copyable_value` is not changed afterwards, or the meaning of your -matcher will be changed. - -## Floating-Point Matchers ## - -| Matcher | Description | -|:-------------------|:---------------------------------------------------------------------------------------------------------| -|`DoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. | -|`FloatEq(a_float)` |`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | -|`NanSensitiveDoubleEq(a_double)`|`argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | -|`NanSensitiveFloatEq(a_float)`|`argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | - -The above matchers use ULP-based comparison (the same as used in -[Google Test](../../googletest/)). They -automatically pick a reasonable error bound based on the absolute -value of the expected value. `DoubleEq()` and `FloatEq()` conform to -the IEEE standard, which requires comparing two NaNs for equality to -return false. The `NanSensitive*` version instead treats two NaNs as -equal, which is often what a user wants. - -| Matcher | Description | -|:--------|:------------| -|`DoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal.| -|`FloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal.| -|`NanSensitiveDoubleNear(a_double, max_abs_error)`|`argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal.| -|`NanSensitiveFloatNear(a_float, max_abs_error)`|`argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal.| - -## String Matchers ## - -The `argument` can be either a C string or a C++ string object: - -| Matcher | Description | -|:----------------------|:--------------------------------------------------| -|`ContainsRegex(string)`|`argument` matches the given regular expression. | -|`EndsWith(suffix)` |`argument` ends with string `suffix`. | -|`HasSubstr(string)` |`argument` contains `string` as a sub-string. | -|`MatchesRegex(string)` |`argument` matches the given regular expression with the match starting at the first character and ending at the last character.| -|`StartsWith(prefix)` |`argument` starts with string `prefix`. | -|`StrCaseEq(string)` |`argument` is equal to `string`, ignoring case. | -|`StrCaseNe(string)` |`argument` is not equal to `string`, ignoring case.| -|`StrEq(string)` |`argument` is equal to `string`. | -|`StrNe(string)` |`argument` is not equal to `string`. | - -`ContainsRegex()` and `MatchesRegex()` use the regular expression -syntax defined -[here](../../googletest/docs/advanced.md#regular-expression-syntax). -`StrCaseEq()`, `StrCaseNe()`, `StrEq()`, and `StrNe()` work for wide -strings as well. - -## Container Matchers ## - -Most STL-style containers support `==`, so you can use -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. If you want to write the elements in-line, -match them more flexibly, or get more informative messages, you can use: - -| Matcher | Description | -|:--------|:------------| -| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | -| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | -| `Each(e)` | `argument` is a container where _every_ element matches `e`, which can be either a value or a matcher. | -| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the i-th element matches `ei`, which can be a value or a matcher. 0 to 10 arguments are allowed. | -| `ElementsAreArray({ e0, e1, ..., en })`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. | -| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | -| `Pointwise(m, container)` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | -| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | -| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under some permutation each element matches an `ei` (for a different `i`), which can be a value or a matcher. 0 to 10 arguments are allowed. | -| `UnorderedElementsAreArray({ e0, e1, ..., en })`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, or C-style array. | -| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements `1`, `2`, and `3`, ignoring order. | -| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. | - -Notes: - - * These matchers can also match: - 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), and - 1. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, int len)` -- see [Multi-argument Matchers](#multiargument-matchers)). - * The array being matched may be multi-dimensional (i.e. its elements can be arrays). - * `m` in `Pointwise(m, ...)` should be a matcher for `::testing::tuple` where `T` and `U` are the element type of the actual container and the expected container, respectively. For example, to compare two `Foo` containers where `Foo` doesn't support `operator==` but has an `Equals()` method, one might write: - -```cpp -using ::testing::get; -MATCHER(FooEq, "") { - return get<0>(arg).Equals(get<1>(arg)); -} -... -EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); -``` - -## Member Matchers ## - -| Matcher | Description | -|:--------|:------------| -|`Field(&class::field, m)`|`argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| -|`Key(e)`|`argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`.| -|`Pair(m1, m2)`|`argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`.| -|`Property(&class::property, m)`|`argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_.| - -## Matching the Result of a Function or Functor ## - -| Matcher | Description | -|:---------------|:---------------------------------------------------------------------| -|`ResultOf(f, m)`|`f(argument)` matches matcher `m`, where `f` is a function or functor.| - -## Pointer Matchers ## - -| Matcher | Description | -|:------------------------|:-----------------------------------------------------------------------------------------------| -|`Pointee(m)` |`argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`.| -|`WhenDynamicCastTo(m)`| when `argument` is passed through `dynamic_cast()`, it matches matcher `m`. | - -## Multiargument Matchers ## - -Technically, all matchers match a _single_ value. A "multi-argument" -matcher is just one that matches a _tuple_. The following matchers can -be used to match a tuple `(x, y)`: - -| Matcher | Description | -|:--------|:------------| -|`Eq()`|`x == y`| -|`Ge()`|`x >= y`| -|`Gt()`|`x > y` | -|`Le()`|`x <= y`| -|`Lt()`|`x < y` | -|`Ne()`|`x != y`| - -You can use the following selectors to pick a subset of the arguments -(or reorder them) to participate in the matching: - -| Matcher | Description | -|:--------|:------------| -|`AllArgs(m)`|Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`.| -|`Args(m)`|The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`.| - -## Composite Matchers ## - -You can make a matcher from one or more other matchers: - -| Matcher | Description | -|:-----------------------|:------------------------------------------------------------| -|`AllOf(m1, m2, ..., mn)`|`argument` matches all of the matchers `m1` to `mn`. | -|`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| -|`Not(m)` |`argument` doesn't match matcher `m`. | - -## Adapters for Matchers ## - -| Matcher | Description | -|:--------|:------------| -|`MatcherCast(m)`|casts matcher `m` to type `Matcher`.| -|`SafeMatcherCast(m)`| [safely casts](CookBook.md#casting-matchers) matcher `m` to type `Matcher`.| -|`Truly(predicate)`|`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| - -## Matchers as Predicates ## - -| Matcher | Description | -|:--------|:------------| -|`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.| -|`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`.| -|`Value(value, m)`|evaluates to `true` if `value` matches `m`.| - -## Defining Matchers ## - -| Matcher | Description | -|:--------|:------------| -| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | -| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | -| `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | - -**Notes:** - - 1. The `MATCHER*` macros cannot be used inside a function or class. - 1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). - 1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. - -## Matchers as Test Assertions ## - -| Matcher | Description | -|:--------|:------------| -|`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/primer.md#assertions) if the value of `expression` doesn't match matcher `m`.| -|`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`.| - -# Actions # - -**Actions** specify what a mock function should do when invoked. - -## Returning a Value ## - -| Matcher | Description | -|:--------|:------------| -|`Return()`|Return from a `void` mock function.| -|`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type at the time the expectation is set, not when the action is executed.| -|`ReturnArg()`|Return the `N`-th (0-based) argument.| -|`ReturnNew(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| -|`ReturnNull()`|Return a null pointer.| -|`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.| -|`ReturnRef(variable)`|Return a reference to `variable`.| -|`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.| - -## Side Effects ## - -| Matcher | Description | -|:--------|:------------| -|`Assign(&variable, value)`|Assign `value` to variable.| -|`DeleteArg()`| Delete the `N`-th (0-based) argument, which must be a pointer.| -|`SaveArg(pointer)`| Save the `N`-th (0-based) argument to `*pointer`.| -|`SaveArgPointee(pointer)`| Save the value pointed to by the `N`-th (0-based) argument to `*pointer`.| -|`SetArgReferee(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | -|`SetArgPointee(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.| -|`SetArgumentPointee(value)`|Same as `SetArgPointee(value)`. Deprecated. Will be removed in v1.7.0.| -|`SetArrayArgument(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| -|`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| -|`Throw(exception)`|Throws the given exception, which can be any copyable value. Available since v1.1.0.| - -## Using a Function or a Functor as an Action ## - -| Matcher | Description | -|:--------|:------------| -|`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| -|`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function.| -|`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments.| -|`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments.| -|`InvokeArgument(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| - -The return value of the invoked function is used as the return value -of the action. - -When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: -```cpp - double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } - ... - EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); -``` - -In `InvokeArgument(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, -```cpp - InvokeArgument<2>(5, string("Hi"), ByRef(foo)) -``` -calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. - -## Default Action ## - -| Matcher | Description | -|:--------|:------------| -|`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| - -**Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. - -## Composite Actions ## - -| Matcher | Description | -|:-----------------------------|:-----------------------------------------------------------------------------------------------------------------------------| -|`DoAll(a1, a2, ..., an)` |Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | -|`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | -|`WithArg(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | -|`WithArgs(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | -|`WithoutArgs(a)` |Perform action `a` without any arguments. | - -## Defining Actions ## - -| Matcher | Description | -|:----------------------------------------------|:------------------------------------------------------------------------------------------| -| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | -| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | -| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | - -The `ACTION*` macros cannot be used inside a function or class. - -# Cardinalities # - -These are used in `Times()` to specify how many times a mock function will be called: - -| Matcher | Description | -|:--------|:------------| -|`AnyNumber()`|The function can be called any number of times.| -|`AtLeast(n)`|The call is expected at least `n` times.| -|`AtMost(n)`|The call is expected at most `n` times.| -|`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| -|`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| - -# Expectation Order # - -By default, the expectations can be matched in _any_ order. If some -or all expectations must be matched in a given order, there are two -ways to specify it. They can be used either independently or -together. - -## The After Clause ## - -```cpp -using ::testing::Expectation; -... -Expectation init_x = EXPECT_CALL(foo, InitX()); -Expectation init_y = EXPECT_CALL(foo, InitY()); -EXPECT_CALL(foo, Bar()) - .After(init_x, init_y); -``` -says that `Bar()` can be called only after both `InitX()` and -`InitY()` have been called. - -If you don't know how many pre-requisites an expectation has when you -write it, you can use an `ExpectationSet` to collect them: - -```cpp -using ::testing::ExpectationSet; -... -ExpectationSet all_inits; -for (int i = 0; i < element_count; i++) { - all_inits += EXPECT_CALL(foo, InitElement(i)); -} -EXPECT_CALL(foo, Bar()) - .After(all_inits); -``` -says that `Bar()` can be called only after all elements have been -initialized (but we don't care about which elements get initialized -before the others). - -Modifying an `ExpectationSet` after using it in an `.After()` doesn't -affect the meaning of the `.After()`. - -## Sequences ## - -When you have a long chain of sequential expectations, it's easier to -specify the order using **sequences**, which don't require you to given -each expectation in the chain a different name. All expected
-calls
in the same sequence must occur in the order they are -specified. - -```cpp -using ::testing::Sequence; -Sequence s1, s2; -... -EXPECT_CALL(foo, Reset()) - .InSequence(s1, s2) - .WillOnce(Return(true)); -EXPECT_CALL(foo, GetSize()) - .InSequence(s1) - .WillOnce(Return(1)); -EXPECT_CALL(foo, Describe(A())) - .InSequence(s2) - .WillOnce(Return("dummy")); -``` -says that `Reset()` must be called before _both_ `GetSize()` _and_ -`Describe()`, and the latter two can occur in any order. - -To put many expectations in a sequence conveniently: -```cpp -using ::testing::InSequence; -{ - InSequence dummy; - - EXPECT_CALL(...)...; - EXPECT_CALL(...)...; - ... - EXPECT_CALL(...)...; -} -``` -says that all expected calls in the scope of `dummy` must occur in -strict order. The name `dummy` is irrelevant.) - -# Verifying and Resetting a Mock # - -Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: -```cpp -using ::testing::Mock; -... -// Verifies and removes the expectations on mock_obj; -// returns true iff successful. -Mock::VerifyAndClearExpectations(&mock_obj); -... -// Verifies and removes the expectations on mock_obj; -// also removes the default actions set by ON_CALL(); -// returns true iff successful. -Mock::VerifyAndClear(&mock_obj); -``` - -You can also tell Google Mock that a mock object can be leaked and doesn't -need to be verified: -```cpp -Mock::AllowLeak(&mock_obj); -``` - -# Mock Classes # - -Google Mock defines a convenient mock class template -```cpp -class MockFunction { - public: - MOCK_METHODn(Call, R(A1, ..., An)); -}; -``` -See this [recipe](CookBook.md#using-check-points) for one application of it. - -# Flags # - -| Flag | Description | -|:--------|:------------| -| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | -| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/CookBook.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/CookBook.md deleted file mode 100644 index 52091109a3c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/CookBook.md +++ /dev/null @@ -1,3660 +0,0 @@ - - -You can find recipes for using Google Mock here. If you haven't yet, -please read the [ForDummies](ForDummies.md) document first to make sure you understand -the basics. - -**Note:** Google Mock lives in the `testing` name space. For -readability, it is recommended to write `using ::testing::Foo;` once in -your file before using the name `Foo` defined by Google Mock. We omit -such `using` statements in this page for brevity, but you should do it -in your own code. - -# Creating Mock Classes # - -## Mocking Private or Protected Methods ## - -You must always put a mock method definition (`MOCK_METHOD*`) in a -`public:` section of the mock class, regardless of the method being -mocked being `public`, `protected`, or `private` in the base class. -This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function -from outside of the mock class. (Yes, C++ allows a subclass to specify -a different access level than the base class on a virtual function.) -Example: - -```cpp -class Foo { - public: - ... - virtual bool Transform(Gadget* g) = 0; - - protected: - virtual void Resume(); - - private: - virtual int GetTimeOut(); -}; - -class MockFoo : public Foo { - public: - ... - MOCK_METHOD1(Transform, bool(Gadget* g)); - - // The following must be in the public section, even though the - // methods are protected or private in the base class. - MOCK_METHOD0(Resume, void()); - MOCK_METHOD0(GetTimeOut, int()); -}; -``` - -## Mocking Overloaded Methods ## - -You can mock overloaded functions as usual. No special attention is required: - -```cpp -class Foo { - ... - - // Must be virtual as we'll inherit from Foo. - virtual ~Foo(); - - // Overloaded on the types and/or numbers of arguments. - virtual int Add(Element x); - virtual int Add(int times, Element x); - - // Overloaded on the const-ness of this object. - virtual Bar& GetBar(); - virtual const Bar& GetBar() const; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Add, int(Element x)); - MOCK_METHOD2(Add, int(int times, Element x); - - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -``` - -**Note:** if you don't mock all versions of the overloaded method, the -compiler will give you a warning about some methods in the base class -being hidden. To fix that, use `using` to bring them in scope: - -```cpp -class MockFoo : public Foo { - ... - using Foo::Add; - MOCK_METHOD1(Add, int(Element x)); - // We don't want to mock int Add(int times, Element x); - ... -}; -``` - -## Mocking Class Templates ## - -To mock a class template, append `_T` to the `MOCK_*` macros: - -```cpp -template -class StackInterface { - ... - // Must be virtual as we'll inherit from StackInterface. - virtual ~StackInterface(); - - virtual int GetSize() const = 0; - virtual void Push(const Elem& x) = 0; -}; - -template -class MockStack : public StackInterface { - ... - MOCK_CONST_METHOD0_T(GetSize, int()); - MOCK_METHOD1_T(Push, void(const Elem& x)); -}; -``` - -## Mocking Nonvirtual Methods ## - -Google Mock can mock non-virtual functions to be used in what we call _hi-perf -dependency injection_. - -In this case, instead of sharing a common base class with the real -class, your mock class will be _unrelated_ to the real class, but -contain methods with the same signatures. The syntax for mocking -non-virtual methods is the _same_ as mocking virtual methods: - -```cpp -// A simple packet stream class. None of its members is virtual. -class ConcretePacketStream { - public: - void AppendPacket(Packet* new_packet); - const Packet* GetPacket(size_t packet_number) const; - size_t NumberOfPackets() const; - ... -}; - -// A mock packet stream class. It inherits from no other, but defines -// GetPacket() and NumberOfPackets(). -class MockPacketStream { - public: - MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number)); - MOCK_CONST_METHOD0(NumberOfPackets, size_t()); - ... -}; -``` - -Note that the mock class doesn't define `AppendPacket()`, unlike the -real class. That's fine as long as the test doesn't need to call it. - -Next, you need a way to say that you want to use -`ConcretePacketStream` in production code and to use `MockPacketStream` -in tests. Since the functions are not virtual and the two classes are -unrelated, you must specify your choice at _compile time_ (as opposed -to run time). - -One way to do it is to templatize your code that needs to use a packet -stream. More specifically, you will give your code a template type -argument for the type of the packet stream. In production, you will -instantiate your template with `ConcretePacketStream` as the type -argument. In tests, you will instantiate the same template with -`MockPacketStream`. For example, you may write: - -```cpp -template -void CreateConnection(PacketStream* stream) { ... } - -template -class PacketReader { - public: - void ReadPackets(PacketStream* stream, size_t packet_num); -}; -``` - -Then you can use `CreateConnection()` and -`PacketReader` in production code, and use -`CreateConnection()` and -`PacketReader` in tests. - -```cpp - MockPacketStream mock_stream; - EXPECT_CALL(mock_stream, ...)...; - .. set more expectations on mock_stream ... - PacketReader reader(&mock_stream); - ... exercise reader ... -``` - -## Mocking Free Functions ## - -It's possible to use Google Mock to mock a free function (i.e. a -C-style function or a static method). You just need to rewrite your -code to use an interface (abstract class). - -Instead of calling a free function (say, `OpenFile`) directly, -introduce an interface for it and have a concrete subclass that calls -the free function: - -```cpp -class FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) = 0; -}; - -class File : public FileInterface { - public: - ... - virtual bool Open(const char* path, const char* mode) { - return OpenFile(path, mode); - } -}; -``` - -Your code should talk to `FileInterface` to open a file. Now it's -easy to mock out the function. - -This may seem much hassle, but in practice you often have multiple -related functions that you can put in the same interface, so the -per-function syntactic overhead will be much lower. - -If you are concerned about the performance overhead incurred by -virtual functions, and profiling confirms your concern, you can -combine this with the recipe for [mocking non-virtual methods](#mocking-nonvirtual-methods). - -## The Nice, the Strict, and the Naggy ## - -If a mock method has no `EXPECT_CALL` spec but is called, Google Mock -will print a warning about the "uninteresting call". The rationale is: - - * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called. - * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, they can add an `EXPECT_CALL()` to suppress the warning. - -However, sometimes you may want to suppress all "uninteresting call" -warnings, while sometimes you may want the opposite, i.e. to treat all -of them as errors. Google Mock lets you make the decision on a -per-mock-object basis. - -Suppose your test uses a mock class `MockFoo`: - -```cpp -TEST(...) { - MockFoo mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -If a method of `mock_foo` other than `DoThis()` is called, it will be -reported by Google Mock as a warning. However, if you rewrite your -test to use `NiceMock` instead, the warning will be gone, -resulting in a cleaner test output: - -```cpp -using ::testing::NiceMock; - -TEST(...) { - NiceMock mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -`NiceMock` is a subclass of `MockFoo`, so it can be used -wherever `MockFoo` is accepted. - -It also works if `MockFoo`'s constructor takes some arguments, as -`NiceMock` "inherits" `MockFoo`'s constructors: - -```cpp -using ::testing::NiceMock; - -TEST(...) { - NiceMock mock_foo(5, "hi"); // Calls MockFoo(5, "hi"). - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... -} -``` - -The usage of `StrictMock` is similar, except that it makes all -uninteresting calls failures: - -```cpp -using ::testing::StrictMock; - -TEST(...) { - StrictMock mock_foo; - EXPECT_CALL(mock_foo, DoThis()); - ... code that uses mock_foo ... - - // The test will fail if a method of mock_foo other than DoThis() - // is called. -} -``` - -There are some caveats though (I don't like them just as much as the -next guy, but sadly they are side effects of C++'s limitations): - - 1. `NiceMock` and `StrictMock` only work for mock methods defined using the `MOCK_METHOD*` family of macros **directly** in the `MockFoo` class. If a mock method is defined in a **base class** of `MockFoo`, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting `NiceMock` and `StrictMock` (e.g. `NiceMock >`) is **not** supported. - 1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](https://google.github.io/styleguide/cppguide.html). - 1. During the constructor or destructor of `MockFoo`, the mock object is _not_ nice or strict. This may cause surprises if the constructor or destructor calls a mock method on `this` object. (This behavior, however, is consistent with C++'s general rule: if a constructor or destructor calls a virtual method of `this` object, that method is treated as non-virtual. In other words, to the base class's constructor or destructor, `this` object behaves like an instance of the base class, not the derived class. This rule is required for safety. Otherwise a base constructor may use members of a derived class before they are initialized, or a base destructor may use members of a derived class after they have been destroyed.) - -Finally, you should be **very cautious** about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you should't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort. - -## Simplifying the Interface without Breaking Existing Code ## - -Sometimes a method has a long list of arguments that is mostly -uninteresting. For example, - -```cpp -class LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, - const struct tm* tm_time, - const char* message, size_t message_len) = 0; -}; -``` - -This method's argument list is lengthy and hard to work with (let's -say that the `message` argument is not even 0-terminated). If we mock -it as is, using the mock will be awkward. If, however, we try to -simplify this interface, we'll need to fix all clients depending on -it, which is often infeasible. - -The trick is to re-dispatch the method in the mock class: - -```cpp -class ScopedMockLog : public LogSink { - public: - ... - virtual void send(LogSeverity severity, const char* full_filename, - const char* base_filename, int line, const tm* tm_time, - const char* message, size_t message_len) { - // We are only interested in the log severity, full file name, and - // log message. - Log(severity, full_filename, std::string(message, message_len)); - } - - // Implements the mock method: - // - // void Log(LogSeverity severity, - // const string& file_path, - // const string& message); - MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path, - const string& message)); -}; -``` - -By defining a new mock method with a trimmed argument list, we make -the mock class much more user-friendly. - -## Alternative to Mocking Concrete Classes ## - -Often you may find yourself using classes that don't implement -interfaces. In order to test your code that uses such a class (let's -call it `Concrete`), you may be tempted to make the methods of -`Concrete` virtual and then mock it. - -Try not to do that. - -Making a non-virtual function virtual is a big decision. It creates an -extension point where subclasses can tweak your class' behavior. This -weakens your control on the class because now it's harder to maintain -the class' invariants. You should make a function virtual only when -there is a valid reason for a subclass to override it. - -Mocking concrete classes directly is problematic as it creates a tight -coupling between the class and the tests - any small change in the -class may invalidate your tests and make test maintenance a pain. - -To avoid such problems, many programmers have been practicing "coding -to interfaces": instead of talking to the `Concrete` class, your code -would define an interface and talk to it. Then you implement that -interface as an adaptor on top of `Concrete`. In tests, you can easily -mock that interface to observe how your code is doing. - -This technique incurs some overhead: - - * You pay the cost of virtual function calls (usually not a problem). - * There is more abstraction for the programmers to learn. - -However, it can also bring significant benefits in addition to better -testability: - - * `Concrete`'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive. - * If `Concrete`'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change. - -Some people worry that if everyone is practicing this technique, they -will end up writing lots of redundant code. This concern is totally -understandable. However, there are two reasons why it may not be the -case: - - * Different projects may need to use `Concrete` in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of `Concrete`, and they will not be the same code. - * If enough projects want to use the same interface, they can always share it, just like they have been sharing `Concrete`. You can check in the interface and the adaptor somewhere near `Concrete` (perhaps in a `contrib` sub-directory) and let many projects use it. - -You need to weigh the pros and cons carefully for your particular -problem, but I'd like to assure you that the Java community has been -practicing this for a long time and it's a proven effective technique -applicable in a wide variety of situations. :-) - -## Delegating Calls to a Fake ## - -Some times you have a non-trivial fake implementation of an -interface. For example: - -```cpp -class Foo { - public: - virtual ~Foo() {} - virtual char DoThis(int n) = 0; - virtual void DoThat(const char* s, int* p) = 0; -}; - -class FakeFoo : public Foo { - public: - virtual char DoThis(int n) { - return (n > 0) ? '+' : - (n < 0) ? '-' : '0'; - } - - virtual void DoThat(const char* s, int* p) { - *p = strlen(s); - } -}; -``` - -Now you want to mock this interface such that you can set expectations -on it. However, you also want to use `FakeFoo` for the default -behavior, as duplicating it in the mock object is, well, a lot of -work. - -When you define the mock class using Google Mock, you can have it -delegate its default action to a fake class you already have, using -this pattern: - -```cpp -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - // Normal mock method definitions using Google Mock. - MOCK_METHOD1(DoThis, char(int n)); - MOCK_METHOD2(DoThat, void(const char* s, int* p)); - - // Delegates the default actions of the methods to a FakeFoo object. - // This must be called *before* the custom ON_CALL() statements. - void DelegateToFake() { - ON_CALL(*this, DoThis(_)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis)); - ON_CALL(*this, DoThat(_, _)) - .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat)); - } - private: - FakeFoo fake_; // Keeps an instance of the fake in the mock. -}; -``` - -With that, you can use `MockFoo` in your tests as usual. Just remember -that if you don't explicitly set an action in an `ON_CALL()` or -`EXPECT_CALL()`, the fake will be called upon to do it: - -```cpp -using ::testing::_; - -TEST(AbcTest, Xyz) { - MockFoo foo; - foo.DelegateToFake(); // Enables the fake for delegation. - - // Put your ON_CALL(foo, ...)s here, if any. - - // No action specified, meaning to use the default action. - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(foo, DoThat(_, _)); - - int n = 0; - EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked. - foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked. - EXPECT_EQ(2, n); -} -``` - -**Some tips:** - - * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`. - * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use. - * The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of `ON_CALL()`), see the "Selecting Between Overloaded Functions" section on this page; to disambiguate a fake function (the one you place inside `Invoke()`), use a `static_cast` to specify the function's type. For instance, if class `Foo` has methods `char DoThis(int n)` and `bool DoThis(double x) const`, and you want to invoke the latter, you need to write `Invoke(&fake_, static_cast(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)` (The strange-looking thing inside the angled brackets of `static_cast` is the type of a function pointer to the second `DoThis()` method.). - * Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, **don't abuse this**. We would only recommend to do it as an intermediate step when you are refactoring your code. - -Regarding the tip on mixing a mock and a fake, here's an example on -why it may be a bad sign: Suppose you have a class `System` for -low-level system operations. In particular, it does file and I/O -operations. And suppose you want to test how your code uses `System` -to do I/O, and you just want the file operations to work normally. If -you mock out the entire `System` class, you'll have to provide a fake -implementation for the file operation part, which suggests that -`System` is taking on too many roles. - -Instead, you can define a `FileOps` interface and an `IOOps` interface -and split `System`'s functionalities into the two. Then you can mock -`IOOps` without mocking `FileOps`. - -## Delegating Calls to a Real Object ## - -When using testing doubles (mocks, fakes, stubs, and etc), sometimes -their behaviors will differ from those of the real objects. This -difference could be either intentional (as in simulating an error such -that you can test the error handling code) or unintentional. If your -mocks have different behaviors than the real objects by mistake, you -could end up with code that passes the tests but fails in production. - -You can use the _delegating-to-real_ technique to ensure that your -mock has the same behavior as the real object while retaining the -ability to validate calls. This technique is very similar to the -delegating-to-fake technique, the difference being that we use a real -object instead of a fake. Here's an example: - -```cpp -using ::testing::_; -using ::testing::AtLeast; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MockFoo() { - // By default, all calls are delegated to the real object. - ON_CALL(*this, DoThis()) - .WillByDefault(Invoke(&real_, &Foo::DoThis)); - ON_CALL(*this, DoThat(_)) - .WillByDefault(Invoke(&real_, &Foo::DoThat)); - ... - } - MOCK_METHOD0(DoThis, ...); - MOCK_METHOD1(DoThat, ...); - ... - private: - Foo real_; -}; -... - - MockFoo mock; - - EXPECT_CALL(mock, DoThis()) - .Times(3); - EXPECT_CALL(mock, DoThat("Hi")) - .Times(AtLeast(1)); - ... use mock in test ... -``` - -With this, Google Mock will verify that your code made the right calls -(with the right arguments, in the right order, called the right number -of times, etc), and a real object will answer the calls (so the -behavior will be the same as in production). This gives you the best -of both worlds. - -## Delegating Calls to a Parent Class ## - -Ideally, you should code to interfaces, whose methods are all pure -virtual. In reality, sometimes you do need to mock a virtual method -that is not pure (i.e, it already has an implementation). For example: - -```cpp -class Foo { - public: - virtual ~Foo(); - - virtual void Pure(int n) = 0; - virtual int Concrete(const char* str) { ... } -}; - -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); -}; -``` - -Sometimes you may want to call `Foo::Concrete()` instead of -`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub -action, or perhaps your test doesn't need to mock `Concrete()` at all -(but it would be oh-so painful to have to define a new mock class -whenever you don't need to mock one of its methods). - -The trick is to leave a back door in your mock class for accessing the -real methods in the base class: - -```cpp -class MockFoo : public Foo { - public: - // Mocking a pure method. - MOCK_METHOD1(Pure, void(int n)); - // Mocking a concrete method. Foo::Concrete() is shadowed. - MOCK_METHOD1(Concrete, int(const char* str)); - - // Use this to call Concrete() defined in Foo. - int FooConcrete(const char* str) { return Foo::Concrete(str); } -}; -``` - -Now, you can call `Foo::Concrete()` inside an action by: - -```cpp -using ::testing::_; -using ::testing::Invoke; -... - EXPECT_CALL(foo, Concrete(_)) - .WillOnce(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -or tell the mock object that you don't want to mock `Concrete()`: - -```cpp -using ::testing::Invoke; -... - ON_CALL(foo, Concrete(_)) - .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete)); -``` - -(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do -that, `MockFoo::Concrete()` will be called (and cause an infinite -recursion) since `Foo::Concrete()` is virtual. That's just how C++ -works.) - -# Using Matchers # - -## Matching Argument Values Exactly ## - -You can specify exactly which arguments a mock method is expecting: - -```cpp -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(5)) - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", bar)); -``` - -## Using Simple Matchers ## - -You can use matchers to match arguments that have a certain property: - -```cpp -using ::testing::Ge; -using ::testing::NotNull; -using ::testing::Return; -... - EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5. - .WillOnce(Return('a')); - EXPECT_CALL(foo, DoThat("Hello", NotNull())); - // The second argument must not be NULL. -``` - -A frequently used matcher is `_`, which matches anything: - -```cpp -using ::testing::_; -using ::testing::NotNull; -... - EXPECT_CALL(foo, DoThat(_, NotNull())); -``` - -## Combining Matchers ## - -You can build complex matchers from existing ones using `AllOf()`, -`AnyOf()`, and `Not()`: - -```cpp -using ::testing::AllOf; -using ::testing::Gt; -using ::testing::HasSubstr; -using ::testing::Ne; -using ::testing::Not; -... - // The argument must be > 5 and != 10. - EXPECT_CALL(foo, DoThis(AllOf(Gt(5), - Ne(10)))); - - // The first argument must not contain sub-string "blah". - EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")), - NULL)); -``` - -## Casting Matchers ## - -Google Mock matchers are statically typed, meaning that the compiler -can catch your mistake if you use a matcher of the wrong type (for -example, if you use `Eq(5)` to match a `string` argument). Good for -you! - -Sometimes, however, you know what you're doing and want the compiler -to give you some slack. One example is that you have a matcher for -`long` and the argument you want to match is `int`. While the two -types aren't exactly the same, there is nothing really wrong with -using a `Matcher` to match an `int` - after all, we can first -convert the `int` argument to a `long` before giving it to the -matcher. - -To support this need, Google Mock gives you the -`SafeMatcherCast(m)` function. It casts a matcher `m` to type -`Matcher`. To ensure safety, Google Mock checks that (let `U` be the -type `m` accepts): - - 1. Type `T` can be implicitly cast to type `U`; - 1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and - 1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value). - -The code won't compile if any of these conditions aren't met. - -Here's one example: - -```cpp -using ::testing::SafeMatcherCast; - -// A base class and a child class. -class Base { ... }; -class Derived : public Base { ... }; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(DoThis, void(Derived* derived)); -}; -... - - MockFoo foo; - // m is a Matcher we got from somewhere. - EXPECT_CALL(foo, DoThis(SafeMatcherCast(m))); -``` - -If you find `SafeMatcherCast(m)` too limiting, you can use a similar -function `MatcherCast(m)`. The difference is that `MatcherCast` works -as long as you can `static_cast` type `T` to type `U`. - -`MatcherCast` essentially lets you bypass C++'s type system -(`static_cast` isn't always safe as it could throw away information, -for example), so be careful not to misuse/abuse it. - -## Selecting Between Overloaded Functions ## - -If you expect an overloaded function to be called, the compiler may -need some help on which overloaded version it is. - -To disambiguate functions overloaded on the const-ness of this object, -use the `Const()` argument wrapper. - -```cpp -using ::testing::ReturnRef; - -class MockFoo : public Foo { - ... - MOCK_METHOD0(GetBar, Bar&()); - MOCK_CONST_METHOD0(GetBar, const Bar&()); -}; -... - - MockFoo foo; - Bar bar1, bar2; - EXPECT_CALL(foo, GetBar()) // The non-const GetBar(). - .WillOnce(ReturnRef(bar1)); - EXPECT_CALL(Const(foo), GetBar()) // The const GetBar(). - .WillOnce(ReturnRef(bar2)); -``` - -(`Const()` is defined by Google Mock and returns a `const` reference -to its argument.) - -To disambiguate overloaded functions with the same number of arguments -but different argument types, you may need to specify the exact type -of a matcher, either by wrapping your matcher in `Matcher()`, or -using a matcher whose type is fixed (`TypedEq`, `An()`, -etc): - -```cpp -using ::testing::An; -using ::testing::Lt; -using ::testing::Matcher; -using ::testing::TypedEq; - -class MockPrinter : public Printer { - public: - MOCK_METHOD1(Print, void(int n)); - MOCK_METHOD1(Print, void(char c)); -}; - -TEST(PrinterTest, Print) { - MockPrinter printer; - - EXPECT_CALL(printer, Print(An())); // void Print(int); - EXPECT_CALL(printer, Print(Matcher(Lt(5)))); // void Print(int); - EXPECT_CALL(printer, Print(TypedEq('a'))); // void Print(char); - - printer.Print(3); - printer.Print(6); - printer.Print('a'); -} -``` - -## Performing Different Actions Based on the Arguments ## - -When a mock method is called, the _last_ matching expectation that's -still active will be selected (think "newer overrides older"). So, you -can make a method do different things depending on its argument values -like this: - -```cpp -using ::testing::_; -using ::testing::Lt; -using ::testing::Return; -... - // The default case. - EXPECT_CALL(foo, DoThis(_)) - .WillRepeatedly(Return('b')); - - // The more specific case. - EXPECT_CALL(foo, DoThis(Lt(5))) - .WillRepeatedly(Return('a')); -``` - -Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will -be returned; otherwise `'b'` will be returned. - -## Matching Multiple Arguments as a Whole ## - -Sometimes it's not enough to match the arguments individually. For -example, we may want to say that the first argument must be less than -the second argument. The `With()` clause allows us to match -all arguments of a mock function as a whole. For example, - -```cpp -using ::testing::_; -using ::testing::Lt; -using ::testing::Ne; -... - EXPECT_CALL(foo, InRange(Ne(0), _)) - .With(Lt()); -``` - -says that the first argument of `InRange()` must not be 0, and must be -less than the second argument. - -The expression inside `With()` must be a matcher of type -`Matcher< ::testing::tuple >`, where `A1`, ..., `An` are the -types of the function arguments. - -You can also write `AllArgs(m)` instead of `m` inside `.With()`. The -two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable -than `.With(Lt())`. - -You can use `Args(m)` to match the `n` selected arguments -(as a tuple) against `m`. For example, - -```cpp -using ::testing::_; -using ::testing::AllOf; -using ::testing::Args; -using ::testing::Lt; -... - EXPECT_CALL(foo, Blah(_, _, _)) - .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt()))); -``` - -says that `Blah()` will be called with arguments `x`, `y`, and `z` where -`x < y < z`. - -As a convenience and example, Google Mock provides some matchers for -2-tuples, including the `Lt()` matcher above. See the [CheatSheet](CheatSheet.md) for -the complete list. - -Note that if you want to pass the arguments to a predicate of your own -(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be -written to take a `::testing::tuple` as its argument; Google Mock will pass the `n` selected arguments as _one_ single tuple to the predicate. - -## Using Matchers as Predicates ## - -Have you noticed that a matcher is just a fancy predicate that also -knows how to describe itself? Many existing algorithms take predicates -as arguments (e.g. those defined in STL's `` header), and -it would be a shame if Google Mock matchers are not allowed to -participate. - -Luckily, you can use a matcher where a unary predicate functor is -expected by wrapping it inside the `Matches()` function. For example, - -```cpp -#include -#include - -std::vector v; -... -// How many elements in v are >= 10? -const int count = count_if(v.begin(), v.end(), Matches(Ge(10))); -``` - -Since you can build complex matchers from simpler ones easily using -Google Mock, this gives you a way to conveniently construct composite -predicates (doing the same using STL's `` header is just -painful). For example, here's a predicate that's satisfied by any -number that is >= 0, <= 100, and != 50: - -```cpp -Matches(AllOf(Ge(0), Le(100), Ne(50))) -``` - -## Using Matchers in Google Test Assertions ## - -Since matchers are basically predicates that also know how to describe -themselves, there is a way to take advantage of them in -[Google Test](../../googletest/) assertions. It's -called `ASSERT_THAT` and `EXPECT_THAT`: - -```cpp - ASSERT_THAT(value, matcher); // Asserts that value matches matcher. - EXPECT_THAT(value, matcher); // The non-fatal version. -``` - -For example, in a Google Test test you can write: - -```cpp -#include "gmock/gmock.h" - -using ::testing::AllOf; -using ::testing::Ge; -using ::testing::Le; -using ::testing::MatchesRegex; -using ::testing::StartsWith; -... - - EXPECT_THAT(Foo(), StartsWith("Hello")); - EXPECT_THAT(Bar(), MatchesRegex("Line \\d+")); - ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10))); -``` - -which (as you can probably guess) executes `Foo()`, `Bar()`, and -`Baz()`, and verifies that: - - * `Foo()` returns a string that starts with `"Hello"`. - * `Bar()` returns a string that matches regular expression `"Line \\d+"`. - * `Baz()` returns a number in the range [5, 10]. - -The nice thing about these macros is that _they read like -English_. They generate informative messages too. For example, if the -first `EXPECT_THAT()` above fails, the message will be something like: - -``` -Value of: Foo() - Actual: "Hi, world!" -Expected: starts with "Hello" -``` - -**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the -[Hamcrest](https://github.com/hamcrest/) project, which adds -`assertThat()` to JUnit. - -## Using Predicates as Matchers ## - -Google Mock provides a built-in set of matchers. In case you find them -lacking, you can use an arbitray unary predicate function or functor -as a matcher - as long as the predicate accepts a value of the type -you want. You do this by wrapping the predicate inside the `Truly()` -function, for example: - -```cpp -using ::testing::Truly; - -int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; } -... - - // Bar() must be called with an even number. - EXPECT_CALL(foo, Bar(Truly(IsEven))); -``` - -Note that the predicate function / functor doesn't have to return -`bool`. It works as long as the return value can be used as the -condition in statement `if (condition) ...`. - -## Matching Arguments that Are Not Copyable ## - -When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves -away a copy of `bar`. When `Foo()` is called later, Google Mock -compares the argument to `Foo()` with the saved copy of `bar`. This -way, you don't need to worry about `bar` being modified or destroyed -after the `EXPECT_CALL()` is executed. The same is true when you use -matchers like `Eq(bar)`, `Le(bar)`, and so on. - -But what if `bar` cannot be copied (i.e. has no copy constructor)? You -could define your own matcher function and use it with `Truly()`, as -the previous couple of recipes have shown. Or, you may be able to get -away from it if you can guarantee that `bar` won't be changed after -the `EXPECT_CALL()` is executed. Just tell Google Mock that it should -save a reference to `bar`, instead of a copy of it. Here's how: - -```cpp -using ::testing::Eq; -using ::testing::ByRef; -using ::testing::Lt; -... - // Expects that Foo()'s argument == bar. - EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar)))); - - // Expects that Foo()'s argument < bar. - EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar)))); -``` - -Remember: if you do this, don't change `bar` after the -`EXPECT_CALL()`, or the result is undefined. - -## Validating a Member of an Object ## - -Often a mock function takes a reference to object as an argument. When -matching the argument, you may not want to compare the entire object -against a fixed object, as that may be over-specification. Instead, -you may need to validate a certain member variable or the result of a -certain getter method of the object. You can do this with `Field()` -and `Property()`. More specifically, - -```cpp -Field(&Foo::bar, m) -``` - -is a matcher that matches a `Foo` object whose `bar` member variable -satisfies matcher `m`. - -```cpp -Property(&Foo::baz, m) -``` - -is a matcher that matches a `Foo` object whose `baz()` method returns -a value that satisfies matcher `m`. - -For example: - -| Expression | Description | -|:-----------------------------|:-----------------------------------| -| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. | -| `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. | - -Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no -argument and be declared as `const`. - -BTW, `Field()` and `Property()` can also match plain pointers to -objects. For instance, - -```cpp -Field(&Foo::number, Ge(3)) -``` - -matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, -the match will always fail regardless of the inner matcher. - -What if you want to validate more than one members at the same time? -Remember that there is `AllOf()`. - -## Validating the Value Pointed to by a Pointer Argument ## - -C++ functions often take pointers as arguments. You can use matchers -like `IsNull()`, `NotNull()`, and other comparison matchers to match a -pointer, but what if you want to make sure the value _pointed to_ by -the pointer, instead of the pointer itself, has a certain property? -Well, you can use the `Pointee(m)` matcher. - -`Pointee(m)` matches a pointer iff `m` matches the value the pointer -points to. For example: - -```cpp -using ::testing::Ge; -using ::testing::Pointee; -... - EXPECT_CALL(foo, Bar(Pointee(Ge(3)))); -``` - -expects `foo.Bar()` to be called with a pointer that points to a value -greater than or equal to 3. - -One nice thing about `Pointee()` is that it treats a `NULL` pointer as -a match failure, so you can write `Pointee(m)` instead of - -```cpp - AllOf(NotNull(), Pointee(m)) -``` - -without worrying that a `NULL` pointer will crash your test. - -Also, did we tell you that `Pointee()` works with both raw pointers -**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and -etc)? - -What if you have a pointer to pointer? You guessed it - you can use -nested `Pointee()` to probe deeper inside the value. For example, -`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer -that points to a number less than 3 (what a mouthful...). - -## Testing a Certain Property of an Object ## - -Sometimes you want to specify that an object argument has a certain -property, but there is no existing matcher that does this. If you want -good error messages, you should define a matcher. If you want to do it -quick and dirty, you could get away with writing an ordinary function. - -Let's say you have a mock function that takes an object of type `Foo`, -which has an `int bar()` method and an `int baz()` method, and you -want to constrain that the argument's `bar()` value plus its `baz()` -value is a given number. Here's how you can define a matcher to do it: - -```cpp -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class BarPlusBazEqMatcher : public MatcherInterface { - public: - explicit BarPlusBazEqMatcher(int expected_sum) - : expected_sum_(expected_sum) {} - - virtual bool MatchAndExplain(const Foo& foo, - MatchResultListener* listener) const { - return (foo.bar() + foo.baz()) == expected_sum_; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "bar() + baz() equals " << expected_sum_; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "bar() + baz() does not equal " << expected_sum_; - } - private: - const int expected_sum_; -}; - -inline Matcher BarPlusBazEq(int expected_sum) { - return MakeMatcher(new BarPlusBazEqMatcher(expected_sum)); -} - -... - - EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...; -``` - -## Matching Containers ## - -Sometimes an STL container (e.g. list, vector, map, ...) is passed to -a mock function and you may want to validate it. Since most STL -containers support the `==` operator, you can write -`Eq(expected_container)` or simply `expected_container` to match a -container exactly. - -Sometimes, though, you may want to be more flexible (for example, the -first element must be an exact match, but the second element can be -any positive number, and so on). Also, containers used in tests often -have a small number of elements, and having to define the expected -container out-of-line is a bit of a hassle. - -You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in -such cases: - -```cpp -using ::testing::_; -using ::testing::ElementsAre; -using ::testing::Gt; -... - - MOCK_METHOD1(Foo, void(const vector& numbers)); -... - - EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5))); -``` - -The above matcher says that the container must have 4 elements, which -must be 1, greater than 0, anything, and 5 respectively. - -If you instead write: - -```cpp -using ::testing::_; -using ::testing::Gt; -using ::testing::UnorderedElementsAre; -... - - MOCK_METHOD1(Foo, void(const vector& numbers)); -... - - EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5))); -``` - -It means that the container must have 4 elements, which under some -permutation must be 1, greater than 0, anything, and 5 respectively. - -`ElementsAre()` and `UnorderedElementsAre()` are overloaded to take 0 -to 10 arguments. If more are needed, you can place them in a C-style -array and use `ElementsAreArray()` or `UnorderedElementsAreArray()` -instead: - -```cpp -using ::testing::ElementsAreArray; -... - - // ElementsAreArray accepts an array of element values. - const int expected_vector1[] = { 1, 5, 2, 4, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1))); - - // Or, an array of element matchers. - Matcher expected_vector2 = { 1, Gt(2), _, 3, ... }; - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2))); -``` - -In case the array needs to be dynamically created (and therefore the -array size cannot be inferred by the compiler), you can give -`ElementsAreArray()` an additional argument to specify the array size: - -```cpp -using ::testing::ElementsAreArray; -... - int* const expected_vector3 = new int[count]; - ... fill expected_vector3 with values ... - EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count))); -``` - -**Tips:** - - * `ElementsAre*()` can be used to match _any_ container that implements the STL iterator pattern (i.e. it has a `const_iterator` type and supports `begin()/end()`), not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern. - * You can use nested `ElementsAre*()` to match nested (multi-dimensional) containers. - * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`. - * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`). - -## Sharing Matchers ## - -Under the hood, a Google Mock matcher object consists of a pointer to -a ref-counted implementation object. Copying matchers is allowed and -very efficient, as only the pointer is copied. When the last matcher -that references the implementation object dies, the implementation -object will be deleted. - -Therefore, if you have some complex matcher that you want to use again -and again, there is no need to build it every time. Just assign it to a -matcher variable and use that variable repeatedly! For example, - -```cpp - Matcher in_range = AllOf(Gt(5), Le(10)); - ... use in_range as a matcher in multiple EXPECT_CALLs ... -``` - -# Setting Expectations # - -## Knowing When to Expect ## - -`ON_CALL` is likely the single most under-utilized construct in Google Mock. - -There are basically two constructs for defining the behavior of a mock object: `ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when a mock method is called, but _doesn't imply any expectation on the method being called._ `EXPECT_CALL` not only defines the behavior, but also sets an expectation that _the method will be called with the given arguments, for the given number of times_ (and _in the given order_ when you specify the order too). - -Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every `EXPECT_CALL` adds a constraint on the behavior of the code under test. Having more constraints than necessary is _baaad_ - even worse than not having enough constraints. - -This may be counter-intuitive. How could tests that verify more be worse than tests that verify less? Isn't verification the whole point of tests? - -The answer, lies in _what_ a test should verify. **A good test verifies the contract of the code.** If a test over-specifies, it doesn't leave enough freedom to the implementation. As a result, changing the implementation without breaking the contract (e.g. refactoring and optimization), which should be perfectly fine to do, can break such tests. Then you have to spend time fixing them, only to see them broken again the next time the implementation is changed. - -Keep in mind that one doesn't have to verify more than one property in one test. In fact, **it's a good style to verify only one thing in one test.** If you do that, a bug will likely break only one or two tests instead of dozens (which case would you rather debug?). If you are also in the habit of giving tests descriptive names that tell what they verify, you can often easily guess what's wrong just from the test log itself. - -So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend to verify that the call is made. For example, you may have a bunch of `ON_CALL`s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s to verify different aspects of the code's behavior. Compared with the style where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more resilient to implementational changes (and thus less likely to require maintenance) and makes the intent of the tests more obvious (so they are easier to maintain when you do need to maintain them). - -If you are bothered by the "Uninteresting mock function call" message printed when a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock` instead to suppress all such messages for the mock object, or suppress the message for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO NOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test that's a pain to maintain. - -## Ignoring Uninteresting Calls ## - -If you are not interested in how a mock method is called, just don't -say anything about it. In this case, if the method is ever called, -Google Mock will perform its default action to allow the test program -to continue. If you are not happy with the default action taken by -Google Mock, you can override it using `DefaultValue::Set()` -(described later in this document) or `ON_CALL()`. - -Please note that once you expressed interest in a particular mock -method (via `EXPECT_CALL()`), all invocations to it must match some -expectation. If this function is called but the arguments don't match -any `EXPECT_CALL()` statement, it will be an error. - -## Disallowing Unexpected Calls ## - -If a mock method shouldn't be called at all, explicitly say so: - -```cpp -using ::testing::_; -... - EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -If some calls to the method are allowed, but the rest are not, just -list all the expected calls: - -```cpp -using ::testing::AnyNumber; -using ::testing::Gt; -... - EXPECT_CALL(foo, Bar(5)); - EXPECT_CALL(foo, Bar(Gt(10))) - .Times(AnyNumber()); -``` - -A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` -statements will be an error. - -## Understanding Uninteresting vs Unexpected Calls ## - -_Uninteresting_ calls and _unexpected_ calls are different concepts in Google Mock. _Very_ different. - -A call `x.Y(...)` is **uninteresting** if there's _not even a single_ `EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the `x.Y()` method at all, as evident in that the test doesn't care to say anything about it. - -A call `x.Y(...)` is **unexpected** if there are some `EXPECT_CALL(x, Y(...))s` set, but none of them matches the call. Put another way, the test is interested in the `x.Y()` method (therefore it _explicitly_ sets some `EXPECT_CALL` to verify how it's called); however, the verification fails as the test doesn't expect this particular call to happen. - -**An unexpected call is always an error,** as the code under test doesn't behave the way the test expects it to behave. - -**By default, an uninteresting call is not an error,** as it violates no constraint specified by the test. (Google Mock's philosophy is that saying nothing means there is no constraint.) However, it leads to a warning, as it _might_ indicate a problem (e.g. the test author might have forgotten to specify a constraint). - -In Google Mock, `NiceMock` and `StrictMock` can be used to make a mock class "nice" or "strict". How does this affect uninteresting calls and unexpected calls? - -A **nice mock** suppresses uninteresting call warnings. It is less chatty than the default mock, but otherwise is the same. If a test fails with a default mock, it will also fail using a nice mock instead. And vice versa. Don't expect making a mock nice to change the test's result. - -A **strict mock** turns uninteresting call warnings into errors. So making a mock strict may change the test's result. - -Let's look at an example: - -```cpp -TEST(...) { - NiceMock mock_registry; - EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) - .WillRepeatedly(Return("Larry Page")); - - // Use mock_registry in code under test. - ... &mock_registry ... -} -``` - -The sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have `"google.com"` as the argument. If `GetDomainOwner("yahoo.com")` is called, it will be an unexpected call, and thus an error. Having a nice mock doesn't change the severity of an unexpected call. - -So how do we tell Google Mock that `GetDomainOwner()` can be called with some other arguments as well? The standard technique is to add a "catch all" `EXPECT_CALL`: - -```cpp - EXPECT_CALL(mock_registry, GetDomainOwner(_)) - .Times(AnyNumber()); // catches all other calls to this method. - EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) - .WillRepeatedly(Return("Larry Page")); -``` - -Remember that `_` is the wildcard matcher that matches anything. With this, if `GetDomainOwner("google.com")` is called, it will do what the second `EXPECT_CALL` says; if it is called with a different argument, it will do what the first `EXPECT_CALL` says. - -Note that the order of the two `EXPECT_CALLs` is important, as a newer `EXPECT_CALL` takes precedence over an older one. - -For more on uninteresting calls, nice mocks, and strict mocks, read ["The Nice, the Strict, and the Naggy"](#the-nice-the-strict-and-the-naggy). - -## Expecting Ordered Calls ## - -Although an `EXPECT_CALL()` statement defined earlier takes precedence -when Google Mock tries to match a function call with an expectation, -by default calls don't have to happen in the order `EXPECT_CALL()` -statements are written. For example, if the arguments match the -matchers in the third `EXPECT_CALL()`, but not those in the first two, -then the third expectation will be used. - -If you would rather have all calls occur in the order of the -expectations, put the `EXPECT_CALL()` statements in a block where you -define a variable of type `InSequence`: - -```cpp - using ::testing::_; - using ::testing::InSequence; - - { - InSequence s; - - EXPECT_CALL(foo, DoThis(5)); - EXPECT_CALL(bar, DoThat(_)) - .Times(2); - EXPECT_CALL(foo, DoThis(6)); - } -``` - -In this example, we expect a call to `foo.DoThis(5)`, followed by two -calls to `bar.DoThat()` where the argument can be anything, which are -in turn followed by a call to `foo.DoThis(6)`. If a call occurred -out-of-order, Google Mock will report an error. - -## Expecting Partially Ordered Calls ## - -Sometimes requiring everything to occur in a predetermined order can -lead to brittle tests. For example, we may care about `A` occurring -before both `B` and `C`, but aren't interested in the relative order -of `B` and `C`. In this case, the test should reflect our real intent, -instead of being overly constraining. - -Google Mock allows you to impose an arbitrary DAG (directed acyclic -graph) on the calls. One way to express the DAG is to use the -[After](CheatSheet.md#the-after-clause) clause of `EXPECT_CALL`. - -Another way is via the `InSequence()` clause (not the same as the -`InSequence` class), which we borrowed from jMock 2. It's less -flexible than `After()`, but more convenient when you have long chains -of sequential calls, as it doesn't require you to come up with -different names for the expectations in the chains. Here's how it -works: - -If we view `EXPECT_CALL()` statements as nodes in a graph, and add an -edge from node A to node B wherever A must occur before B, we can get -a DAG. We use the term "sequence" to mean a directed path in this -DAG. Now, if we decompose the DAG into sequences, we just need to know -which sequences each `EXPECT_CALL()` belongs to in order to be able to -reconstruct the original DAG. - -So, to specify the partial order on the expectations we need to do two -things: first to define some `Sequence` objects, and then for each -`EXPECT_CALL()` say which `Sequence` objects it is part -of. Expectations in the same sequence must occur in the order they are -written. For example, - -```cpp - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(foo, A()) - .InSequence(s1, s2); - EXPECT_CALL(bar, B()) - .InSequence(s1); - EXPECT_CALL(bar, C()) - .InSequence(s2); - EXPECT_CALL(foo, D()) - .InSequence(s2); -``` - -specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> -C -> D`): - -``` - +---> B - | - A ---| - | - +---> C ---> D -``` - -This means that A must occur before B and C, and C must occur before -D. There's no restriction about the order other than these. - -## Controlling When an Expectation Retires ## - -When a mock method is called, Google Mock only consider expectations -that are still active. An expectation is active when created, and -becomes inactive (aka _retires_) when a call that has to occur later -has occurred. For example, in - -```cpp - using ::testing::_; - using ::testing::Sequence; - - Sequence s1, s2; - - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1 - .Times(AnyNumber()) - .InSequence(s1, s2); - EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2 - .InSequence(s1); - EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3 - .InSequence(s2); -``` - -as soon as either #2 or #3 is matched, #1 will retire. If a warning -`"File too large."` is logged after this, it will be an error. - -Note that an expectation doesn't retire automatically when it's -saturated. For example, - -```cpp -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2 -``` - -says that there will be exactly one warning with the message `"File -too large."`. If the second warning contains this message too, #2 will -match again and result in an upper-bound-violated error. - -If this is not what you want, you can ask an expectation to retire as -soon as it becomes saturated: - -```cpp -using ::testing::_; -... - EXPECT_CALL(log, Log(WARNING, _, _)); // #1 - EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2 - .RetiresOnSaturation(); -``` - -Here #2 can be used only once, so if you have two warnings with the -message `"File too large."`, the first will match #2 and the second -will match #1 - there will be no error. - -# Using Actions # - -## Returning References from Mock Methods ## - -If a mock function's return type is a reference, you need to use -`ReturnRef()` instead of `Return()` to return a result: - -```cpp -using ::testing::ReturnRef; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetBar, Bar&()); -}; -... - - MockFoo foo; - Bar bar; - EXPECT_CALL(foo, GetBar()) - .WillOnce(ReturnRef(bar)); -``` - -## Returning Live Values from Mock Methods ## - -The `Return(x)` action saves a copy of `x` when the action is -_created_, and always returns the same value whenever it's -executed. Sometimes you may want to instead return the _live_ value of -`x` (i.e. its value at the time when the action is _executed_.). - -If the mock function's return type is a reference, you can do it using -`ReturnRef(x)`, as shown in the previous recipe ("Returning References -from Mock Methods"). However, Google Mock doesn't let you use -`ReturnRef()` in a mock function whose return type is not a reference, -as doing that usually indicates a user error. So, what shall you do? - -You may be tempted to try `ByRef()`: - -```cpp -using testing::ByRef; -using testing::Return; - -class MockFoo : public Foo { - public: - MOCK_METHOD0(GetValue, int()); -}; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(Return(ByRef(x))); - x = 42; - EXPECT_EQ(42, foo.GetValue()); -``` - -Unfortunately, it doesn't work here. The above code will fail with error: - -``` -Value of: foo.GetValue() - Actual: 0 -Expected: 42 -``` - -The reason is that `Return(value)` converts `value` to the actual -return type of the mock function at the time when the action is -_created_, not when it is _executed_. (This behavior was chosen for -the action to be safe when `value` is a proxy object that references -some temporary objects.) As a result, `ByRef(x)` is converted to an -`int` value (instead of a `const int&`) when the expectation is set, -and `Return(ByRef(x))` will always return 0. - -`ReturnPointee(pointer)` was provided to solve this problem -specifically. It returns the value pointed to by `pointer` at the time -the action is _executed_: - -```cpp -using testing::ReturnPointee; -... - int x = 0; - MockFoo foo; - EXPECT_CALL(foo, GetValue()) - .WillRepeatedly(ReturnPointee(&x)); // Note the & here. - x = 42; - EXPECT_EQ(42, foo.GetValue()); // This will succeed now. -``` - -## Combining Actions ## - -Want to do more than one thing when a function is called? That's -fine. `DoAll()` allow you to do sequence of actions every time. Only -the return value of the last action in the sequence will be used. - -```cpp -using ::testing::DoAll; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Bar, bool(int n)); -}; -... - - EXPECT_CALL(foo, Bar(_)) - .WillOnce(DoAll(action_1, - action_2, - ... - action_n)); -``` - -## Mocking Side Effects ## - -Sometimes a method exhibits its effect not via returning a value but -via side effects. For example, it may change some global state or -modify an output argument. To mock side effects, in general you can -define your own action by implementing `::testing::ActionInterface`. - -If all you need to do is to change an output argument, the built-in -`SetArgPointee()` action is convenient: - -```cpp -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - MOCK_METHOD2(Mutate, void(bool mutate, int* value)); - ... -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, Mutate(true, _)) - .WillOnce(SetArgPointee<1>(5)); -``` - -In this example, when `mutator.Mutate()` is called, we will assign 5 -to the `int` variable pointed to by argument #1 -(0-based). - -`SetArgPointee()` conveniently makes an internal copy of the -value you pass to it, removing the need to keep the value in scope and -alive. The implication however is that the value must have a copy -constructor and assignment operator. - -If the mock method also needs to return a value as well, you can chain -`SetArgPointee()` with `Return()` using `DoAll()`: - -```cpp -using ::testing::_; -using ::testing::Return; -using ::testing::SetArgPointee; - -class MockMutator : public Mutator { - public: - ... - MOCK_METHOD1(MutateInt, bool(int* value)); -}; -... - - MockMutator mutator; - EXPECT_CALL(mutator, MutateInt(_)) - .WillOnce(DoAll(SetArgPointee<0>(5), - Return(true))); -``` - -If the output argument is an array, use the -`SetArrayArgument(first, last)` action instead. It copies the -elements in source range `[first, last)` to the array pointed to by -the `N`-th (0-based) argument: - -```cpp -using ::testing::NotNull; -using ::testing::SetArrayArgument; - -class MockArrayMutator : public ArrayMutator { - public: - MOCK_METHOD2(Mutate, void(int* values, int num_values)); - ... -}; -... - - MockArrayMutator mutator; - int values[5] = { 1, 2, 3, 4, 5 }; - EXPECT_CALL(mutator, Mutate(NotNull(), 5)) - .WillOnce(SetArrayArgument<0>(values, values + 5)); -``` - -This also works when the argument is an output iterator: - -```cpp -using ::testing::_; -using ::testing::SetArrayArgument; - -class MockRolodex : public Rolodex { - public: - MOCK_METHOD1(GetNames, void(std::back_insert_iterator >)); - ... -}; -... - - MockRolodex rolodex; - vector names; - names.push_back("George"); - names.push_back("John"); - names.push_back("Thomas"); - EXPECT_CALL(rolodex, GetNames(_)) - .WillOnce(SetArrayArgument<0>(names.begin(), names.end())); -``` - -## Changing a Mock Object's Behavior Based on the State ## - -If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call: - -```cpp -using ::testing::InSequence; -using ::testing::Return; - -... - { - InSequence seq; - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(true)); - EXPECT_CALL(my_mock, Flush()); - EXPECT_CALL(my_mock, IsDirty()) - .WillRepeatedly(Return(false)); - } - my_mock.FlushIfDirty(); -``` - -This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards. - -If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable: - -```cpp -using ::testing::_; -using ::testing::SaveArg; -using ::testing::Return; - -ACTION_P(ReturnPointee, p) { return *p; } -... - int previous_value = 0; - EXPECT_CALL(my_mock, GetPrevValue()) - .WillRepeatedly(ReturnPointee(&previous_value)); - EXPECT_CALL(my_mock, UpdateValue(_)) - .WillRepeatedly(SaveArg<0>(&previous_value)); - my_mock.DoSomethingToUpdateValue(); -``` - -Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call. - -## Setting the Default Value for a Return Type ## - -If a mock method's return type is a built-in C++ type or pointer, by -default it will return 0 when invoked. Also, in C++ 11 and above, a mock -method whose return type has a default constructor will return a default-constructed -value by default. You only need to specify an -action if this default value doesn't work for you. - -Sometimes, you may want to change this default value, or you may want -to specify a default value for types Google Mock doesn't know -about. You can do this using the `::testing::DefaultValue` class -template: - -```cpp -class MockFoo : public Foo { - public: - MOCK_METHOD0(CalculateBar, Bar()); -}; -... - - Bar default_bar; - // Sets the default return value for type Bar. - DefaultValue::Set(default_bar); - - MockFoo foo; - - // We don't need to specify an action here, as the default - // return value works for us. - EXPECT_CALL(foo, CalculateBar()); - - foo.CalculateBar(); // This should return default_bar. - - // Unsets the default return value. - DefaultValue::Clear(); -``` - -Please note that changing the default value for a type can make you -tests hard to understand. We recommend you to use this feature -judiciously. For example, you may want to make sure the `Set()` and -`Clear()` calls are right next to the code that uses your mock. - -## Setting the Default Actions for a Mock Method ## - -You've learned how to change the default value of a given -type. However, this may be too coarse for your purpose: perhaps you -have two mock methods with the same return type and you want them to -have different behaviors. The `ON_CALL()` macro allows you to -customize your mock's behavior at the method level: - -```cpp -using ::testing::_; -using ::testing::AnyNumber; -using ::testing::Gt; -using ::testing::Return; -... - ON_CALL(foo, Sign(_)) - .WillByDefault(Return(-1)); - ON_CALL(foo, Sign(0)) - .WillByDefault(Return(0)); - ON_CALL(foo, Sign(Gt(0))) - .WillByDefault(Return(1)); - - EXPECT_CALL(foo, Sign(_)) - .Times(AnyNumber()); - - foo.Sign(5); // This should return 1. - foo.Sign(-9); // This should return -1. - foo.Sign(0); // This should return 0. -``` - -As you may have guessed, when there are more than one `ON_CALL()` -statements, the news order take precedence over the older ones. In -other words, the **last** one that matches the function arguments will -be used. This matching order allows you to set up the common behavior -in a mock object's constructor or the test fixture's set-up phase and -specialize the mock's behavior later. - -## Using Functions/Methods/Functors as Actions ## - -If the built-in actions don't suit you, you can easily use an existing -function, method, or functor as an action: - -```cpp -using ::testing::_; -using ::testing::Invoke; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(Sum, int(int x, int y)); - MOCK_METHOD1(ComplexJob, bool(int x)); -}; - -int CalculateSum(int x, int y) { return x + y; } - -class Helper { - public: - bool ComplexJob(int x); -}; -... - - MockFoo foo; - Helper helper; - EXPECT_CALL(foo, Sum(_, _)) - .WillOnce(Invoke(CalculateSum)); - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(Invoke(&helper, &Helper::ComplexJob)); - - foo.Sum(5, 6); // Invokes CalculateSum(5, 6). - foo.ComplexJob(10); // Invokes helper.ComplexJob(10); -``` - -The only requirement is that the type of the function, etc must be -_compatible_ with the signature of the mock function, meaning that the -latter's arguments can be implicitly converted to the corresponding -arguments of the former, and the former's return type can be -implicitly converted to that of the latter. So, you can invoke -something whose type is _not_ exactly the same as the mock function, -as long as it's safe to do so - nice, huh? - -## Invoking a Function/Method/Functor Without Arguments ## - -`Invoke()` is very useful for doing actions that are more complex. It -passes the mock function's arguments to the function or functor being -invoked such that the callee has the full context of the call to work -with. If the invoked function is not interested in some or all of the -arguments, it can simply ignore them. - -Yet, a common pattern is that a test author wants to invoke a function -without the arguments of the mock function. `Invoke()` allows her to -do that using a wrapper function that throws away the arguments before -invoking an underlining nullary function. Needless to say, this can be -tedious and obscures the intent of the test. - -`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except -that it doesn't pass the mock function's arguments to the -callee. Here's an example: - -```cpp -using ::testing::_; -using ::testing::InvokeWithoutArgs; - -class MockFoo : public Foo { - public: - MOCK_METHOD1(ComplexJob, bool(int n)); -}; - -bool Job1() { ... } -... - - MockFoo foo; - EXPECT_CALL(foo, ComplexJob(_)) - .WillOnce(InvokeWithoutArgs(Job1)); - - foo.ComplexJob(10); // Invokes Job1(). -``` - -## Invoking an Argument of the Mock Function ## - -Sometimes a mock function will receive a function pointer or a functor -(in other words, a "callable") as an argument, e.g. - -```cpp -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int))); -}; -``` - -and you may want to invoke this callable argument: - -```cpp -using ::testing::_; -... - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(...); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -Arghh, you need to refer to a mock function argument but your version -of C++ has no lambdas, so you have to define your own action. :-( -Or do you really? - -Well, Google Mock has an action to solve _exactly_ this problem: - -```cpp - InvokeArgument(arg_1, arg_2, ..., arg_m) -``` - -will invoke the `N`-th (0-based) argument the mock function receives, -with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is -a function pointer or a functor, Google Mock handles them both. - -With that, you could write: - -```cpp -using ::testing::_; -using ::testing::InvokeArgument; -... - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(InvokeArgument<1>(5)); - // Will execute (*fp)(5), where fp is the - // second argument DoThis() receives. -``` - -What if the callable takes an argument by reference? No problem - just -wrap it inside `ByRef()`: - -```cpp -... - MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&))); -... -using ::testing::_; -using ::testing::ByRef; -using ::testing::InvokeArgument; -... - - MockFoo foo; - Helper helper; - ... - EXPECT_CALL(foo, Bar(_)) - .WillOnce(InvokeArgument<0>(5, ByRef(helper))); - // ByRef(helper) guarantees that a reference to helper, not a copy of it, - // will be passed to the callable. -``` - -What if the callable takes an argument by reference and we do **not** -wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a -copy_ of the argument, and pass a _reference to the copy_, instead of -a reference to the original value, to the callable. This is especially -handy when the argument is a temporary value: - -```cpp -... - MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s))); -... -using ::testing::_; -using ::testing::InvokeArgument; -... - - MockFoo foo; - ... - EXPECT_CALL(foo, DoThat(_)) - .WillOnce(InvokeArgument<0>(5.0, string("Hi"))); - // Will execute (*f)(5.0, string("Hi")), where f is the function pointer - // DoThat() receives. Note that the values 5.0 and string("Hi") are - // temporary and dead once the EXPECT_CALL() statement finishes. Yet - // it's fine to perform this action later, since a copy of the values - // are kept inside the InvokeArgument action. -``` - -## Ignoring an Action's Result ## - -Sometimes you have an action that returns _something_, but you need an -action that returns `void` (perhaps you want to use it in a mock -function that returns `void`, or perhaps it needs to be used in -`DoAll()` and it's not the last in the list). `IgnoreResult()` lets -you do that. For example: - -```cpp -using ::testing::_; -using ::testing::Invoke; -using ::testing::Return; - -int Process(const MyData& data); -string DoSomething(); - -class MockFoo : public Foo { - public: - MOCK_METHOD1(Abc, void(const MyData& data)); - MOCK_METHOD0(Xyz, bool()); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, Abc(_)) - // .WillOnce(Invoke(Process)); - // The above line won't compile as Process() returns int but Abc() needs - // to return void. - .WillOnce(IgnoreResult(Invoke(Process))); - - EXPECT_CALL(foo, Xyz()) - .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)), - // Ignores the string DoSomething() returns. - Return(true))); -``` - -Note that you **cannot** use `IgnoreResult()` on an action that already -returns `void`. Doing so will lead to ugly compiler errors. - -## Selecting an Action's Arguments ## - -Say you have a mock function `Foo()` that takes seven arguments, and -you have a custom action that you want to invoke when `Foo()` is -called. Trouble is, the custom action only wants three arguments: - -```cpp -using ::testing::_; -using ::testing::Invoke; -... - MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y, - const map, double>& weight, - double min_weight, double max_wight)); -... - -bool IsVisibleInQuadrant1(bool visible, int x, int y) { - return visible && x >= 0 && y >= 0; -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-( -``` - -To please the compiler God, you can to define an "adaptor" that has -the same signature as `Foo()` and calls the custom action with the -right arguments: - -```cpp -using ::testing::_; -using ::testing::Invoke; - -bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y, - const map, double>& weight, - double min_weight, double max_wight) { - return IsVisibleInQuadrant1(visible, x, y); -} -... - - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works. -``` - -But isn't this awkward? - -Google Mock provides a generic _action adaptor_, so you can spend your -time minding more important business than writing your own -adaptors. Here's the syntax: - -```cpp - WithArgs(action) -``` - -creates an action that passes the arguments of the mock function at -the given indices (0-based) to the inner `action` and performs -it. Using `WithArgs`, our original example can be written as: - -```cpp -using ::testing::_; -using ::testing::Invoke; -using ::testing::WithArgs; -... - EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _)) - .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1))); - // No need to define your own adaptor. -``` - -For better readability, Google Mock also gives you: - - * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and - * `WithArg(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument. - -As you may have realized, `InvokeWithoutArgs(...)` is just syntactic -sugar for `WithoutArgs(Invoke(...))`. - -Here are more tips: - - * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything. - * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`. - * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`. - * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work. - -## Ignoring Arguments in Action Functions ## - -The selecting-an-action's-arguments recipe showed us one way to make a -mock function and an action with incompatible argument lists fit -together. The downside is that wrapping the action in -`WithArgs<...>()` can get tedious for people writing the tests. - -If you are defining a function, method, or functor to be used with -`Invoke*()`, and you are not interested in some of its arguments, an -alternative to `WithArgs` is to declare the uninteresting arguments as -`Unused`. This makes the definition less cluttered and less fragile in -case the types of the uninteresting arguments change. It could also -increase the chance the action function can be reused. For example, -given - -```cpp - MOCK_METHOD3(Foo, double(const string& label, double x, double y)); - MOCK_METHOD3(Bar, double(int index, double x, double y)); -``` - -instead of - -```cpp -using ::testing::_; -using ::testing::Invoke; - -double DistanceToOriginWithLabel(const string& label, double x, double y) { - return sqrt(x*x + y*y); -} - -double DistanceToOriginWithIndex(int index, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOriginWithLabel)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOriginWithIndex)); -``` - -you could write - -```cpp -using ::testing::_; -using ::testing::Invoke; -using ::testing::Unused; - -double DistanceToOrigin(Unused, double x, double y) { - return sqrt(x*x + y*y); -} -... - - EXEPCT_CALL(mock, Foo("abc", _, _)) - .WillOnce(Invoke(DistanceToOrigin)); - EXEPCT_CALL(mock, Bar(5, _, _)) - .WillOnce(Invoke(DistanceToOrigin)); -``` - -## Sharing Actions ## - -Just like matchers, a Google Mock action object consists of a pointer -to a ref-counted implementation object. Therefore copying actions is -also allowed and very efficient. When the last action that references -the implementation object dies, the implementation object will be -deleted. - -If you have some complex action that you want to use again and again, -you may not have to build it from scratch every time. If the action -doesn't have an internal state (i.e. if it always does the same thing -no matter how many times it has been called), you can assign it to an -action variable and use that variable repeatedly. For example: - -```cpp - Action set_flag = DoAll(SetArgPointee<0>(5), - Return(true)); - ... use set_flag in .WillOnce() and .WillRepeatedly() ... -``` - -However, if the action has its own state, you may be surprised if you -share the action object. Suppose you have an action factory -`IncrementCounter(init)` which creates an action that increments and -returns a counter whose initial value is `init`, using two actions -created from the same expression and using a shared action will -exihibit different behaviors. Example: - -```cpp - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(IncrementCounter(0)); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(IncrementCounter(0)); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 1 - Blah() uses a different - // counter than Bar()'s. -``` - -versus - -```cpp - Action increment = IncrementCounter(0); - - EXPECT_CALL(foo, DoThis()) - .WillRepeatedly(increment); - EXPECT_CALL(foo, DoThat()) - .WillRepeatedly(increment); - foo.DoThis(); // Returns 1. - foo.DoThis(); // Returns 2. - foo.DoThat(); // Returns 3 - the counter is shared. -``` - -# Misc Recipes on Using Google Mock # - -## Mocking Methods That Use Move-Only Types ## - -C++11 introduced *move-only types*. A move-only-typed value can be moved from -one object to another, but cannot be copied. `std::unique_ptr` is -probably the most commonly used move-only type. - -Mocking a method that takes and/or returns move-only types presents some -challenges, but nothing insurmountable. This recipe shows you how you can do it. -Note that the support for move-only method arguments was only introduced to -gMock in April 2017; in older code, you may find more complex -[workarounds](#legacy-workarounds-for-move-only-types) for lack of this feature. - -Let’s say we are working on a fictional project that lets one post and share -snippets called “buzzes”. Your code uses these types: - -```cpp -enum class AccessLevel { kInternal, kPublic }; - -class Buzz { - public: - explicit Buzz(AccessLevel access) { ... } - ... -}; - -class Buzzer { - public: - virtual ~Buzzer() {} - virtual std::unique_ptr MakeBuzz(StringPiece text) = 0; - virtual bool ShareBuzz(std::unique_ptr buzz, int64_t timestamp) = 0; - ... -}; -``` - -A `Buzz` object represents a snippet being posted. A class that implements the -`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in -`Buzzer` may return a `unique_ptr` or take a -`unique_ptr`. Now we need to mock `Buzzer` in our tests. - -To mock a method that accepts or returns move-only types, you just use the -familiar `MOCK_METHOD` syntax as usual: - -```cpp -class MockBuzzer : public Buzzer { - public: - MOCK_METHOD1(MakeBuzz, std::unique_ptr(StringPiece text)); - MOCK_METHOD2(ShareBuzz, bool(std::unique_ptr buzz, int64_t timestamp)); -}; -``` - -Now that we have the mock class defined, we can use it in tests. In the -following code examples, we assume that we have defined a `MockBuzzer` object -named `mock_buzzer_`: - -```cpp - MockBuzzer mock_buzzer_; -``` - -First let’s see how we can set expectations on the `MakeBuzz()` method, which -returns a `unique_ptr`. - -As usual, if you set an expectation without an action (i.e. the `.WillOnce()` or -`.WillRepeated()` clause), when that expectation fires, the default action for -that method will be taken. Since `unique_ptr<>` has a default constructor -that returns a null `unique_ptr`, that’s what you’ll get if you don’t specify an -action: - -```cpp - // Use the default action. - EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")); - - // Triggers the previous EXPECT_CALL. - EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz("hello")); -``` - -If you are not happy with the default action, you can tweak it as usual; see -[Setting Default Actions](#setting-the-default-actions-for-a-mock-method). - -If you just need to return a pre-defined move-only value, you can use the -`Return(ByMove(...))` action: - -```cpp - // When this fires, the unique_ptr<> specified by ByMove(...) will - // be returned. - EXPECT_CALL(mock_buzzer_, MakeBuzz("world")) - .WillOnce(Return(ByMove(MakeUnique(AccessLevel::kInternal)))); - - EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("world")); -``` - -Note that `ByMove()` is essential here - if you drop it, the code won’t compile. - -Quiz time! What do you think will happen if a `Return(ByMove(...))` action is -performed more than once (e.g. you write -`.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first -time the action runs, the source value will be consumed (since it’s a move-only -value), so the next time around, there’s no value to move from -- you’ll get a -run-time error that `Return(ByMove(...))` can only be run once. - -If you need your mock method to do more than just moving a pre-defined value, -remember that you can always use a lambda or a callable object, which can do -pretty much anything you want: - -```cpp - EXPECT_CALL(mock_buzzer_, MakeBuzz("x")) - .WillRepeatedly([](StringPiece text) { - return MakeUnique(AccessLevel::kInternal); - }); - - EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); - EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz("x")); -``` - -Every time this `EXPECT_CALL` fires, a new `unique_ptr` will be -created and returned. You cannot do this with `Return(ByMove(...))`. - -That covers returning move-only values; but how do we work with methods -accepting move-only arguments? The answer is that they work normally, although -some actions will not compile when any of method's arguments are move-only. You -can always use `Return`, or a [lambda or functor](#using-functionsmethodsfunctors-as-actions): - -```cpp - using ::testing::Unused; - - EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)) .WillOnce(Return(true)); - EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique(AccessLevel::kInternal)), - 0); - - EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)) .WillOnce( - [](std::unique_ptr buzz, Unused) { return buzz != nullptr; }); - EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0)); -``` - -Many built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...) -could in principle support move-only arguments, but the support for this is not -implemented yet. If this is blocking you, please file a bug. - -A few actions (e.g. `DoAll`) copy their arguments internally, so they can never -work with non-copyable objects; you'll have to use functors instead. - -##### Legacy workarounds for move-only types - -Support for move-only function arguments was only introduced to gMock in April -2017. In older code, you may encounter the following workaround for the lack of -this feature (it is no longer necessary - we're including it just for -reference): - -```cpp -class MockBuzzer : public Buzzer { - public: - MOCK_METHOD2(DoShareBuzz, bool(Buzz* buzz, Time timestamp)); - bool ShareBuzz(std::unique_ptr buzz, Time timestamp) override { - return DoShareBuzz(buzz.get(), timestamp); - } -}; -``` - -The trick is to delegate the `ShareBuzz()` method to a mock method (let’s call -it `DoShareBuzz()`) that does not take move-only parameters. Then, instead of -setting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock -method: - -```cpp - MockBuzzer mock_buzzer_; - EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _)); - - // When one calls ShareBuzz() on the MockBuzzer like this, the call is - // forwarded to DoShareBuzz(), which is mocked. Therefore this statement - // will trigger the above EXPECT_CALL. - mock_buzzer_.ShareBuzz(MakeUnique(AccessLevel::kInternal), 0); -``` - - - -## Making the Compilation Faster ## - -Believe it or not, the _vast majority_ of the time spent on compiling -a mock class is in generating its constructor and destructor, as they -perform non-trivial tasks (e.g. verification of the -expectations). What's more, mock methods with different signatures -have different types and thus their constructors/destructors need to -be generated by the compiler separately. As a result, if you mock many -different types of methods, compiling your mock class can get really -slow. - -If you are experiencing slow compilation, you can move the definition -of your mock class' constructor and destructor out of the class body -and into a `.cpp` file. This way, even if you `#include` your mock -class in N files, the compiler only needs to generate its constructor -and destructor once, resulting in a much faster compilation. - -Let's illustrate the idea using an example. Here's the definition of a -mock class before applying this recipe: - -```cpp -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // Since we don't declare the constructor or the destructor, - // the compiler will generate them in every translation unit - // where this mock class is used. - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` - -After the change, it would look like: - -```cpp -// File mock_foo.h. -... -class MockFoo : public Foo { - public: - // The constructor and destructor are declared, but not defined, here. - MockFoo(); - virtual ~MockFoo(); - - MOCK_METHOD0(DoThis, int()); - MOCK_METHOD1(DoThat, bool(const char* str)); - ... more mock methods ... -}; -``` -and -```cpp -// File mock_foo.cpp. -#include "path/to/mock_foo.h" - -// The definitions may appear trivial, but the functions actually do a -// lot of things through the constructors/destructors of the member -// variables used to implement the mock methods. -MockFoo::MockFoo() {} -MockFoo::~MockFoo() {} -``` - -## Forcing a Verification ## - -When it's being destroyed, your friendly mock object will automatically -verify that all expectations on it have been satisfied, and will -generate [Google Test](../../googletest/) failures -if not. This is convenient as it leaves you with one less thing to -worry about. That is, unless you are not sure if your mock object will -be destroyed. - -How could it be that your mock object won't eventually be destroyed? -Well, it might be created on the heap and owned by the code you are -testing. Suppose there's a bug in that code and it doesn't delete the -mock object properly - you could end up with a passing test when -there's actually a bug. - -Using a heap checker is a good idea and can alleviate the concern, but -its implementation may not be 100% reliable. So, sometimes you do want -to _force_ Google Mock to verify a mock object before it is -(hopefully) destructed. You can do this with -`Mock::VerifyAndClearExpectations(&mock_object)`: - -```cpp -TEST(MyServerTest, ProcessesRequest) { - using ::testing::Mock; - - MockFoo* const foo = new MockFoo; - EXPECT_CALL(*foo, ...)...; - // ... other expectations ... - - // server now owns foo. - MyServer server(foo); - server.ProcessRequest(...); - - // In case that server's destructor will forget to delete foo, - // this will verify the expectations anyway. - Mock::VerifyAndClearExpectations(foo); -} // server is destroyed when it goes out of scope here. -``` - -**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a -`bool` to indicate whether the verification was successful (`true` for -yes), so you can wrap that function call inside a `ASSERT_TRUE()` if -there is no point going further when the verification has failed. - -## Using Check Points ## - -Sometimes you may want to "reset" a mock object at various check -points in your test: at each check point, you verify that all existing -expectations on the mock object have been satisfied, and then you set -some new expectations on it as if it's newly created. This allows you -to work with a mock object in "phases" whose sizes are each -manageable. - -One such scenario is that in your test's `SetUp()` function, you may -want to put the object you are testing into a certain state, with the -help from a mock object. Once in the desired state, you want to clear -all expectations on the mock, such that in the `TEST_F` body you can -set fresh expectations on it. - -As you may have figured out, the `Mock::VerifyAndClearExpectations()` -function we saw in the previous recipe can help you here. Or, if you -are using `ON_CALL()` to set default actions on the mock object and -want to clear the default actions as well, use -`Mock::VerifyAndClear(&mock_object)` instead. This function does what -`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the -same `bool`, **plus** it clears the `ON_CALL()` statements on -`mock_object` too. - -Another trick you can use to achieve the same effect is to put the -expectations in sequences and insert calls to a dummy "check-point" -function at specific places. Then you can verify that the mock -function calls do happen at the right time. For example, if you are -exercising code: - -```cpp -Foo(1); -Foo(2); -Foo(3); -``` - -and want to verify that `Foo(1)` and `Foo(3)` both invoke -`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write: - -```cpp -using ::testing::MockFunction; - -TEST(FooTest, InvokesBarCorrectly) { - MyMock mock; - // Class MockFunction has exactly one mock method. It is named - // Call() and has type F. - MockFunction check; - { - InSequence s; - - EXPECT_CALL(mock, Bar("a")); - EXPECT_CALL(check, Call("1")); - EXPECT_CALL(check, Call("2")); - EXPECT_CALL(mock, Bar("a")); - } - Foo(1); - check.Call("1"); - Foo(2); - check.Call("2"); - Foo(3); -} -``` - -The expectation spec says that the first `Bar("a")` must happen before -check point "1", the second `Bar("a")` must happen after check point "2", -and nothing should happen between the two check points. The explicit -check points make it easy to tell which `Bar("a")` is called by which -call to `Foo()`. - -## Mocking Destructors ## - -Sometimes you want to make sure a mock object is destructed at the -right time, e.g. after `bar->A()` is called but before `bar->B()` is -called. We already know that you can specify constraints on the order -of mock function calls, so all we need to do is to mock the destructor -of the mock function. - -This sounds simple, except for one problem: a destructor is a special -function with special syntax and special semantics, and the -`MOCK_METHOD0` macro doesn't work for it: - -```cpp - MOCK_METHOD0(~MockFoo, void()); // Won't compile! -``` - -The good news is that you can use a simple pattern to achieve the same -effect. First, add a mock function `Die()` to your mock class and call -it in the destructor, like this: - -```cpp -class MockFoo : public Foo { - ... - // Add the following two lines to the mock class. - MOCK_METHOD0(Die, void()); - virtual ~MockFoo() { Die(); } -}; -``` - -(If the name `Die()` clashes with an existing symbol, choose another -name.) Now, we have translated the problem of testing when a `MockFoo` -object dies to testing when its `Die()` method is called: - -```cpp - MockFoo* foo = new MockFoo; - MockBar* bar = new MockBar; - ... - { - InSequence s; - - // Expects *foo to die after bar->A() and before bar->B(). - EXPECT_CALL(*bar, A()); - EXPECT_CALL(*foo, Die()); - EXPECT_CALL(*bar, B()); - } -``` - -And that's that. - -## Using Google Mock and Threads ## - -**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on -platforms where Google Mock is thread-safe. Currently these are only -platforms that support the pthreads library (this includes Linux and Mac). -To make it thread-safe on other platforms we only need to implement -some synchronization operations in `"gtest/internal/gtest-port.h"`. - -In a **unit** test, it's best if you could isolate and test a piece of -code in a single-threaded context. That avoids race conditions and -dead locks, and makes debugging your test much easier. - -Yet many programs are multi-threaded, and sometimes to test something -we need to pound on it from more than one thread. Google Mock works -for this purpose too. - -Remember the steps for using a mock: - - 1. Create a mock object `foo`. - 1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`. - 1. The code under test calls methods of `foo`. - 1. Optionally, verify and reset the mock. - 1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it. - -If you follow the following simple rules, your mocks and threads can -live happily together: - - * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow. - * Obviously, you can do step #1 without locking. - * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh? - * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic. - -If you violate the rules (for example, if you set expectations on a -mock while another thread is calling its methods), you get undefined -behavior. That's not fun, so don't do it. - -Google Mock guarantees that the action for a mock function is done in -the same thread that called the mock function. For example, in - -```cpp - EXPECT_CALL(mock, Foo(1)) - .WillOnce(action1); - EXPECT_CALL(mock, Foo(2)) - .WillOnce(action2); -``` - -if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, -Google Mock will execute `action1` in thread 1 and `action2` in thread -2. - -Google Mock does _not_ impose a sequence on actions performed in -different threads (doing so may create deadlocks as the actions may -need to cooperate). This means that the execution of `action1` and -`action2` in the above example _may_ interleave. If this is a problem, -you should add proper synchronization logic to `action1` and `action2` -to make the test thread-safe. - - -Also, remember that `DefaultValue` is a global resource that -potentially affects _all_ living mock objects in your -program. Naturally, you won't want to mess with it from multiple -threads or when there still are mocks in action. - -## Controlling How Much Information Google Mock Prints ## - -When Google Mock sees something that has the potential of being an -error (e.g. a mock function with no expectation is called, a.k.a. an -uninteresting call, which is allowed but perhaps you forgot to -explicitly ban the call), it prints some warning messages, including -the arguments of the function and the return value. Hopefully this -will remind you to take a look and see if there is indeed a problem. - -Sometimes you are confident that your tests are correct and may not -appreciate such friendly messages. Some other times, you are debugging -your tests or learning about the behavior of the code you are testing, -and wish you could observe every mock call that happens (including -argument values and the return value). Clearly, one size doesn't fit -all. - -You can control how much Google Mock tells you using the -`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string -with three possible values: - - * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros. - * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default. - * `error`: Google Mock will print errors only (least verbose). - -Alternatively, you can adjust the value of that flag from within your -tests like so: - -```cpp - ::testing::FLAGS_gmock_verbose = "error"; -``` - -Now, judiciously use the right flag to enable Google Mock serve you better! - -## Gaining Super Vision into Mock Calls ## - -You have a test using Google Mock. It fails: Google Mock tells you -that some expectations aren't satisfied. However, you aren't sure why: -Is there a typo somewhere in the matchers? Did you mess up the order -of the `EXPECT_CALL`s? Or is the code under test doing something -wrong? How can you find out the cause? - -Won't it be nice if you have X-ray vision and can actually see the -trace of all `EXPECT_CALL`s and mock method calls as they are made? -For each call, would you like to see its actual argument values and -which `EXPECT_CALL` Google Mock thinks it matches? - -You can unlock this power by running your test with the -`--gmock_verbose=info` flag. For example, given the test program: - -```cpp -using testing::_; -using testing::HasSubstr; -using testing::Return; - -class MockFoo { - public: - MOCK_METHOD2(F, void(const string& x, const string& y)); -}; - -TEST(Foo, Bar) { - MockFoo mock; - EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return()); - EXPECT_CALL(mock, F("a", "b")); - EXPECT_CALL(mock, F("c", HasSubstr("d"))); - - mock.F("a", "good"); - mock.F("a", "b"); -} -``` - -if you run it with `--gmock_verbose=info`, you will see this output: - -``` -[ RUN ] Foo.Bar - -foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked -foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked -foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked -foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))... - Function call: F(@0x7fff7c8dad40"a", @0x7fff7c8dad10"good") -foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))... - Function call: F(@0x7fff7c8dada0"a", @0x7fff7c8dad70"b") -foo_test.cc:16: Failure -Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))... - Expected: to be called once - Actual: never called - unsatisfied and active -[ FAILED ] Foo.Bar -``` - -Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo -and should actually be `"a"`. With the above message, you should see -that the actual `F("a", "good")` call is matched by the first -`EXPECT_CALL`, not the third as you thought. From that it should be -obvious that the third `EXPECT_CALL` is written wrong. Case solved. - -## Running Tests in Emacs ## - -If you build and run your tests in Emacs, the source file locations of -Google Mock and [Google Test](../../googletest/) -errors will be highlighted. Just press `` on one of them and -you'll be taken to the offending line. Or, you can just type `C-x `` -to jump to the next error. - -To make it even easier, you can add the following lines to your -`~/.emacs` file: - -``` -(global-set-key "\M-m" 'compile) ; m is for make -(global-set-key [M-down] 'next-error) -(global-set-key [M-up] '(lambda () (interactive) (next-error -1))) -``` - -Then you can type `M-m` to start a build, or `M-up`/`M-down` to move -back and forth between errors. - -## Fusing Google Mock Source Files ## - -Google Mock's implementation consists of dozens of files (excluding -its own tests). Sometimes you may want them to be packaged up in -fewer files instead, such that you can easily copy them to a new -machine and start hacking there. For this we provide an experimental -Python script `fuse_gmock_files.py` in the `scripts/` directory -(starting with release 1.2.0). Assuming you have Python 2.4 or above -installed on your machine, just go to that directory and run -``` -python fuse_gmock_files.py OUTPUT_DIR -``` - -and you should see an `OUTPUT_DIR` directory being created with files -`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it. -These three files contain everything you need to use Google Mock (and -Google Test). Just copy them to anywhere you want and you are ready -to write tests and use mocks. You can use the -[make/Makefile](../make/Makefile) file as an example on how to compile your tests -against them. - -# Extending Google Mock # - -## Writing New Matchers Quickly ## - -The `MATCHER*` family of macros can be used to define custom matchers -easily. The syntax: - -```cpp -MATCHER(name, description_string_expression) { statements; } -``` - -will define a matcher with the given name that executes the -statements, which must return a `bool` to indicate if the match -succeeds. Inside the statements, you can refer to the value being -matched by `arg`, and refer to its type by `arg_type`. - -The description string is a `string`-typed expression that documents -what the matcher does, and is used to generate the failure message -when the match fails. It can (and should) reference the special -`bool` variable `negation`, and should evaluate to the description of -the matcher when `negation` is `false`, or that of the matcher's -negation when `negation` is `true`. - -For convenience, we allow the description string to be empty (`""`), -in which case Google Mock will use the sequence of words in the -matcher name as the description. - -For example: -```cpp -MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; } -``` -allows you to write -```cpp - // Expects mock_foo.Bar(n) to be called where n is divisible by 7. - EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7())); -``` -or, -```cpp -using ::testing::Not; -... - EXPECT_THAT(some_expression, IsDivisibleBy7()); - EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7())); -``` -If the above assertions fail, they will print something like: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 -... - Value of: some_other_expression - Expected: not (is divisible by 7) - Actual: 21 -``` -where the descriptions `"is divisible by 7"` and `"not (is divisible -by 7)"` are automatically calculated from the matcher name -`IsDivisibleBy7`. - -As you may have noticed, the auto-generated descriptions (especially -those for the negation) may not be so great. You can always override -them with a string expression of your own: -```cpp -MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") + - " divisible by 7") { - return (arg % 7) == 0; -} -``` - -Optionally, you can stream additional information to a hidden argument -named `result_listener` to explain the match result. For example, a -better definition of `IsDivisibleBy7` is: -```cpp -MATCHER(IsDivisibleBy7, "") { - if ((arg % 7) == 0) - return true; - - *result_listener << "the remainder is " << (arg % 7); - return false; -} -``` - -With this definition, the above assertion will give a better message: -``` - Value of: some_expression - Expected: is divisible by 7 - Actual: 27 (the remainder is 6) -``` - -You should let `MatchAndExplain()` print _any additional information_ -that can help a user understand the match result. Note that it should -explain why the match succeeds in case of a success (unless it's -obvious) - this is useful when the matcher is used inside -`Not()`. There is no need to print the argument value itself, as -Google Mock already prints it for you. - -**Notes:** - - 1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on. - 1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock. - -## Writing New Parameterized Matchers Quickly ## - -Sometimes you'll want to define a matcher that has parameters. For that you -can use the macro: -```cpp -MATCHER_P(name, param_name, description_string) { statements; } -``` -where the description string can be either `""` or a string expression -that references `negation` and `param_name`. - -For example: -```cpp -MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -``` -will allow you to write: -```cpp - EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -``` -which may lead to this message (assuming `n` is 10): -``` - Value of: Blah("a") - Expected: has absolute value 10 - Actual: -9 -``` - -Note that both the matcher description and its parameter are -printed, making the message human-friendly. - -In the matcher definition body, you can write `foo_type` to -reference the type of a parameter named `foo`. For example, in the -body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write -`value_type` to refer to the type of `value`. - -Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to -`MATCHER_P10` to support multi-parameter matchers: -```cpp -MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; } -``` - -Please note that the custom description string is for a particular -**instance** of the matcher, where the parameters have been bound to -actual values. Therefore usually you'll want the parameter values to -be part of the description. Google Mock lets you do that by -referencing the matcher parameters in the description string -expression. - -For example, -```cpp - using ::testing::PrintToString; - MATCHER_P2(InClosedRange, low, hi, - std::string(negation ? "isn't" : "is") + " in range [" + - PrintToString(low) + ", " + PrintToString(hi) + "]") { - return low <= arg && arg <= hi; - } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the message: -``` - Expected: is in range [4, 6] -``` - -If you specify `""` as the description, the failure message will -contain the sequence of words in the matcher name followed by the -parameter values printed as a tuple. For example, -```cpp - MATCHER_P2(InClosedRange, low, hi, "") { ... } - ... - EXPECT_THAT(3, InClosedRange(4, 6)); -``` -would generate a failure that contains the text: -``` - Expected: in closed range (4, 6) -``` - -For the purpose of typing, you can view -```cpp -MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } -``` -as shorthand for -```cpp -template -FooMatcherPk -Foo(p1_type p1, ..., pk_type pk) { ... } -``` - -When you write `Foo(v1, ..., vk)`, the compiler infers the types of -the parameters `v1`, ..., and `vk` for you. If you are not happy with -the result of the type inference, you can specify the types by -explicitly instantiating the template, as in `Foo(5, false)`. -As said earlier, you don't get to (or need to) specify -`arg_type` as that's determined by the context in which the matcher -is used. - -You can assign the result of expression `Foo(p1, ..., pk)` to a -variable of type `FooMatcherPk`. This can be -useful when composing matchers. Matchers that don't have a parameter -or have only one parameter have special types: you can assign `Foo()` -to a `FooMatcher`-typed variable, and assign `Foo(p)` to a -`FooMatcherP`-typed variable. - -While you can instantiate a matcher template with reference types, -passing the parameters by pointer usually makes your code more -readable. If, however, you still want to pass a parameter by -reference, be aware that in the failure message generated by the -matcher you will see the value of the referenced object but not its -address. - -You can overload matchers with different numbers of parameters: -```cpp -MATCHER_P(Blah, a, description_string_1) { ... } -MATCHER_P2(Blah, a, b, description_string_2) { ... } -``` - -While it's tempting to always use the `MATCHER*` macros when defining -a new matcher, you should also consider implementing -`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see -the recipes that follow), especially if you need to use the matcher a -lot. While these approaches require more work, they give you more -control on the types of the value being matched and the matcher -parameters, which in general leads to better compiler error messages -that pay off in the long run. They also allow overloading matchers -based on parameter types (as opposed to just based on the number of -parameters). - -## Writing New Monomorphic Matchers ## - -A matcher of argument type `T` implements -`::testing::MatcherInterface` and does two things: it tests whether a -value of type `T` matches the matcher, and can describe what kind of -values it matches. The latter ability is used for generating readable -error messages when expectations are violated. - -The interface looks like this: - -```cpp -class MatchResultListener { - public: - ... - // Streams x to the underlying ostream; does nothing if the ostream - // is NULL. - template - MatchResultListener& operator<<(const T& x); - - // Returns the underlying ostream. - ::std::ostream* stream(); -}; - -template -class MatcherInterface { - public: - virtual ~MatcherInterface(); - - // Returns true iff the matcher matches x; also explains the match - // result to 'listener'. - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; - - // Describes this matcher to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; - - // Describes the negation of this matcher to an ostream. - virtual void DescribeNegationTo(::std::ostream* os) const; -}; -``` - -If you need a custom matcher but `Truly()` is not a good option (for -example, you may not be happy with the way `Truly(predicate)` -describes itself, or you may want your matcher to be polymorphic as -`Eq(value)` is), you can define a matcher to do whatever you want in -two steps: first implement the matcher interface, and then define a -factory function to create a matcher instance. The second step is not -strictly needed but it makes the syntax of using the matcher nicer. - -For example, you can define a matcher to test whether an `int` is -divisible by 7 and then use it like this: -```cpp -using ::testing::MakeMatcher; -using ::testing::Matcher; -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; - -class DivisibleBy7Matcher : public MatcherInterface { - public: - virtual bool MatchAndExplain(int n, MatchResultListener* listener) const { - return (n % 7) == 0; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "is divisible by 7"; - } - - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "is not divisible by 7"; - } -}; - -inline Matcher DivisibleBy7() { - return MakeMatcher(new DivisibleBy7Matcher); -} -... - - EXPECT_CALL(foo, Bar(DivisibleBy7())); -``` - -You may improve the matcher message by streaming additional -information to the `listener` argument in `MatchAndExplain()`: - -```cpp -class DivisibleBy7Matcher : public MatcherInterface { - public: - virtual bool MatchAndExplain(int n, - MatchResultListener* listener) const { - const int remainder = n % 7; - if (remainder != 0) { - *listener << "the remainder is " << remainder; - } - return remainder == 0; - } - ... -}; -``` - -Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this: -``` -Value of: x -Expected: is divisible by 7 - Actual: 23 (the remainder is 2) -``` - -## Writing New Polymorphic Matchers ## - -You've learned how to write your own matchers in the previous -recipe. Just one problem: a matcher created using `MakeMatcher()` only -works for one particular type of arguments. If you want a -_polymorphic_ matcher that works with arguments of several types (for -instance, `Eq(x)` can be used to match a `value` as long as `value` == -`x` compiles -- `value` and `x` don't have to share the same type), -you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit -involved. - -Fortunately, most of the time you can define a polymorphic matcher -easily with the help of `MakePolymorphicMatcher()`. Here's how you can -define `NotNull()` as an example: - -```cpp -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -using ::testing::NotNull; -using ::testing::PolymorphicMatcher; - -class NotNullMatcher { - public: - // To implement a polymorphic matcher, first define a COPYABLE class - // that has three members MatchAndExplain(), DescribeTo(), and - // DescribeNegationTo(), like the following. - - // In this example, we want to use NotNull() with any pointer, so - // MatchAndExplain() accepts a pointer of any type as its first argument. - // In general, you can define MatchAndExplain() as an ordinary method or - // a method template, or even overload it. - template - bool MatchAndExplain(T* p, - MatchResultListener* /* listener */) const { - return p != NULL; - } - - // Describes the property of a value matching this matcher. - void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; } - - // Describes the property of a value NOT matching this matcher. - void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } -}; - -// To construct a polymorphic matcher, pass an instance of the class -// to MakePolymorphicMatcher(). Note the return type. -inline PolymorphicMatcher NotNull() { - return MakePolymorphicMatcher(NotNullMatcher()); -} -... - - EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer. -``` - -**Note:** Your polymorphic matcher class does **not** need to inherit from -`MatcherInterface` or any other class, and its methods do **not** need -to be virtual. - -Like in a monomorphic matcher, you may explain the match result by -streaming additional information to the `listener` argument in -`MatchAndExplain()`. - -## Writing New Cardinalities ## - -A cardinality is used in `Times()` to tell Google Mock how many times -you expect a call to occur. It doesn't have to be exact. For example, -you can say `AtLeast(5)` or `Between(2, 4)`. - -If the built-in set of cardinalities doesn't suit you, you are free to -define your own by implementing the following interface (in namespace -`testing`): - -```cpp -class CardinalityInterface { - public: - virtual ~CardinalityInterface(); - - // Returns true iff call_count calls will satisfy this cardinality. - virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - - // Returns true iff call_count calls will saturate this cardinality. - virtual bool IsSaturatedByCallCount(int call_count) const = 0; - - // Describes self to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; -}; -``` - -For example, to specify that a call must occur even number of times, -you can write - -```cpp -using ::testing::Cardinality; -using ::testing::CardinalityInterface; -using ::testing::MakeCardinality; - -class EvenNumberCardinality : public CardinalityInterface { - public: - virtual bool IsSatisfiedByCallCount(int call_count) const { - return (call_count % 2) == 0; - } - - virtual bool IsSaturatedByCallCount(int call_count) const { - return false; - } - - virtual void DescribeTo(::std::ostream* os) const { - *os << "called even number of times"; - } -}; - -Cardinality EvenNumber() { - return MakeCardinality(new EvenNumberCardinality); -} -... - - EXPECT_CALL(foo, Bar(3)) - .Times(EvenNumber()); -``` - -## Writing New Actions Quickly ## - -If the built-in actions don't work for you, and you find it -inconvenient to use `Invoke()`, you can use a macro from the `ACTION*` -family to quickly define a new action that can be used in your code as -if it's a built-in action. - -By writing -```cpp -ACTION(name) { statements; } -``` -in a namespace scope (i.e. not inside a class or function), you will -define an action with the given name that executes the statements. -The value returned by `statements` will be used as the return value of -the action. Inside the statements, you can refer to the K-th -(0-based) argument of the mock function as `argK`. For example: -```cpp -ACTION(IncrementArg1) { return ++(*arg1); } -``` -allows you to write -```cpp -... WillOnce(IncrementArg1()); -``` - -Note that you don't need to specify the types of the mock function -arguments. Rest assured that your code is type-safe though: -you'll get a compiler error if `*arg1` doesn't support the `++` -operator, or if the type of `++(*arg1)` isn't compatible with the mock -function's return type. - -Another example: -```cpp -ACTION(Foo) { - (*arg2)(5); - Blah(); - *arg1 = 0; - return arg0; -} -``` -defines an action `Foo()` that invokes argument #2 (a function pointer) -with 5, calls function `Blah()`, sets the value pointed to by argument -#1 to 0, and returns argument #0. - -For more convenience and flexibility, you can also use the following -pre-defined symbols in the body of `ACTION`: - -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -|:----------------|:-------------------------------------------------------------| -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | -| `function_type` | The type of the mock function | - -For example, when using an `ACTION` as a stub action for mock function: -```cpp -int DoSomething(bool flag, int* ptr); -``` -we have: - -| **Pre-defined Symbol** | **Is Bound To** | -|:-----------------------|:----------------| -| `arg0` | the value of `flag` | -| `arg0_type` | the type `bool` | -| `arg1` | the value of `ptr` | -| `arg1_type` | the type `int*` | -| `args` | the tuple `(flag, ptr)` | -| `args_type` | the type `::testing::tuple` | -| `return_type` | the type `int` | -| `function_type` | the type `int(bool, int*)` | - -## Writing New Parameterized Actions Quickly ## - -Sometimes you'll want to parameterize an action you define. For that -we have another macro -```cpp -ACTION_P(name, param) { statements; } -``` - -For example, -```cpp -ACTION_P(Add, n) { return arg0 + n; } -``` -will allow you to write -```cpp -// Returns argument #0 + 5. -... WillOnce(Add(5)); -``` - -For convenience, we use the term _arguments_ for the values used to -invoke the mock function, and the term _parameters_ for the values -used to instantiate an action. - -Note that you don't need to provide the type of the parameter either. -Suppose the parameter is named `param`, you can also use the -Google-Mock-defined symbol `param_type` to refer to the type of the -parameter as inferred by the compiler. For example, in the body of -`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`. - -Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support -multi-parameter actions. For example, -```cpp -ACTION_P2(ReturnDistanceTo, x, y) { - double dx = arg0 - x; - double dy = arg1 - y; - return sqrt(dx*dx + dy*dy); -} -``` -lets you write -```cpp -... WillOnce(ReturnDistanceTo(5.0, 26.5)); -``` - -You can view `ACTION` as a degenerated parameterized action where the -number of parameters is 0. - -You can also easily define actions overloaded on the number of parameters: -```cpp -ACTION_P(Plus, a) { ... } -ACTION_P2(Plus, a, b) { ... } -``` - -## Restricting the Type of an Argument or Parameter in an ACTION ## - -For maximum brevity and reusability, the `ACTION*` macros don't ask -you to provide the types of the mock function arguments and the action -parameters. Instead, we let the compiler infer the types for us. - -Sometimes, however, we may want to be more explicit about the types. -There are several tricks to do that. For example: -```cpp -ACTION(Foo) { - // Makes sure arg0 can be converted to int. - int n = arg0; - ... use n instead of arg0 here ... -} - -ACTION_P(Bar, param) { - // Makes sure the type of arg1 is const char*. - ::testing::StaticAssertTypeEq(); - - // Makes sure param can be converted to bool. - bool flag = param; -} -``` -where `StaticAssertTypeEq` is a compile-time assertion in Google Test -that verifies two types are the same. - -## Writing New Action Templates Quickly ## - -Sometimes you want to give an action explicit template parameters that -cannot be inferred from its value parameters. `ACTION_TEMPLATE()` -supports that and can be viewed as an extension to `ACTION()` and -`ACTION_P*()`. - -The syntax: -```cpp -ACTION_TEMPLATE(ActionName, - HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), - AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -``` - -defines an action template that takes _m_ explicit template parameters -and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is -between 0 and 10. `name_i` is the name of the i-th template -parameter, and `kind_i` specifies whether it's a `typename`, an -integral constant, or a template. `p_i` is the name of the i-th value -parameter. - -Example: -```cpp -// DuplicateArg(output) converts the k-th argument of the mock -// function to type T and copies it to *output. -ACTION_TEMPLATE(DuplicateArg, - // Note the comma between int and k: - HAS_2_TEMPLATE_PARAMS(int, k, typename, T), - AND_1_VALUE_PARAMS(output)) { - *output = T(::testing::get(args)); -} -``` - -To create an instance of an action template, write: -```cpp - ActionName(v1, ..., v_n) -``` -where the `t`s are the template arguments and the -`v`s are the value arguments. The value argument -types are inferred by the compiler. For example: -```cpp -using ::testing::_; -... - int n; - EXPECT_CALL(mock, Foo(_, _)) - .WillOnce(DuplicateArg<1, unsigned char>(&n)); -``` - -If you want to explicitly specify the value argument types, you can -provide additional template arguments: -```cpp - ActionName(v1, ..., v_n) -``` -where `u_i` is the desired type of `v_i`. - -`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the -number of value parameters, but not on the number of template -parameters. Without the restriction, the meaning of the following is -unclear: - -```cpp - OverloadedAction(x); -``` - -Are we using a single-template-parameter action where `bool` refers to -the type of `x`, or a two-template-parameter action where the compiler -is asked to infer the type of `x`? - -## Using the ACTION Object's Type ## - -If you are writing a function that returns an `ACTION` object, you'll -need to know its type. The type depends on the macro used to define -the action and the parameter types. The rule is relatively simple: - -| **Given Definition** | **Expression** | **Has Type** | -|:---------------------|:---------------|:-------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo()` | `FooAction` | -| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` | -| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar(int_value)` | `FooActionP` | -| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` | -| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))`| `Baz(bool_value, int_value)` | `FooActionP2` | -| ... | ... | ... | - -Note that we have to pick different suffixes (`Action`, `ActionP`, -`ActionP2`, and etc) for actions with different numbers of value -parameters, or the action definitions cannot be overloaded on the -number of them. - -## Writing New Monomorphic Actions ## - -While the `ACTION*` macros are very convenient, sometimes they are -inappropriate. For example, despite the tricks shown in the previous -recipes, they don't let you directly specify the types of the mock -function arguments and the action parameters, which in general leads -to unoptimized compiler error messages that can baffle unfamiliar -users. They also don't allow overloading actions based on parameter -types without jumping through some hoops. - -An alternative to the `ACTION*` macros is to implement -`::testing::ActionInterface`, where `F` is the type of the mock -function in which the action will be used. For example: - -```cpp -template class ActionInterface { - public: - virtual ~ActionInterface(); - - // Performs the action. Result is the return type of function type - // F, and ArgumentTuple is the tuple of arguments of F. - // - // For example, if F is int(bool, const string&), then Result would - // be int, and ArgumentTuple would be ::testing::tuple. - virtual Result Perform(const ArgumentTuple& args) = 0; -}; - -using ::testing::_; -using ::testing::Action; -using ::testing::ActionInterface; -using ::testing::MakeAction; - -typedef int IncrementMethod(int*); - -class IncrementArgumentAction : public ActionInterface { - public: - virtual int Perform(const ::testing::tuple& args) { - int* p = ::testing::get<0>(args); // Grabs the first argument. - return *p++; - } -}; - -Action IncrementArgument() { - return MakeAction(new IncrementArgumentAction); -} -... - - EXPECT_CALL(foo, Baz(_)) - .WillOnce(IncrementArgument()); - - int n = 5; - foo.Baz(&n); // Should return 5 and change n to 6. -``` - -## Writing New Polymorphic Actions ## - -The previous recipe showed you how to define your own action. This is -all good, except that you need to know the type of the function in -which the action will be used. Sometimes that can be a problem. For -example, if you want to use the action in functions with _different_ -types (e.g. like `Return()` and `SetArgPointee()`). - -If an action can be used in several types of mock functions, we say -it's _polymorphic_. The `MakePolymorphicAction()` function template -makes it easy to define such an action: - -```cpp -namespace testing { - -template -PolymorphicAction MakePolymorphicAction(const Impl& impl); - -} // namespace testing -``` - -As an example, let's define an action that returns the second argument -in the mock function's argument list. The first step is to define an -implementation class: - -```cpp -class ReturnSecondArgumentAction { - public: - template - Result Perform(const ArgumentTuple& args) const { - // To get the i-th (0-based) argument, use ::testing::get(args). - return ::testing::get<1>(args); - } -}; -``` - -This implementation class does _not_ need to inherit from any -particular class. What matters is that it must have a `Perform()` -method template. This method template takes the mock function's -arguments as a tuple in a **single** argument, and returns the result of -the action. It can be either `const` or not, but must be invokable -with exactly one template argument, which is the result type. In other -words, you must be able to call `Perform(args)` where `R` is the -mock function's return type and `args` is its arguments in a tuple. - -Next, we use `MakePolymorphicAction()` to turn an instance of the -implementation class into the polymorphic action we need. It will be -convenient to have a wrapper for this: - -```cpp -using ::testing::MakePolymorphicAction; -using ::testing::PolymorphicAction; - -PolymorphicAction ReturnSecondArgument() { - return MakePolymorphicAction(ReturnSecondArgumentAction()); -} -``` - -Now, you can use this polymorphic action the same way you use the -built-in ones: - -```cpp -using ::testing::_; - -class MockFoo : public Foo { - public: - MOCK_METHOD2(DoThis, int(bool flag, int n)); - MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2)); -}; -... - - MockFoo foo; - EXPECT_CALL(foo, DoThis(_, _)) - .WillOnce(ReturnSecondArgument()); - EXPECT_CALL(foo, DoThat(_, _, _)) - .WillOnce(ReturnSecondArgument()); - ... - foo.DoThis(true, 5); // Will return 5. - foo.DoThat(1, "Hi", "Bye"); // Will return "Hi". -``` - -## Teaching Google Mock How to Print Your Values ## - -When an uninteresting or unexpected call occurs, Google Mock prints the -argument values and the stack trace to help you debug. Assertion -macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in -question when the assertion fails. Google Mock and Google Test do this using -Google Test's user-extensible value printer. - -This printer knows how to print built-in C++ types, native arrays, STL -containers, and any type that supports the `<<` operator. For other -types, it prints the raw bytes in the value and hopes that you the -user can figure it out. -[Google Test's advanced guide](../../googletest/docs/advanced.md#teaching-googletest-how-to-print-your-values) -explains how to extend the printer to do a better job at -printing your particular type than to dump the bytes. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/DesignDoc.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/DesignDoc.md deleted file mode 100644 index 4cddc9d0a38..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/DesignDoc.md +++ /dev/null @@ -1,282 +0,0 @@ -This page discusses the design of new Google Mock features. - - - -# Macros for Defining Actions # - -## Problem ## - -Due to the lack of closures in C++, it currently requires some -non-trivial effort to define a custom action in Google Mock. For -example, suppose you want to "increment the value pointed to by the -second argument of the mock function and return it", you could write: - -```cpp -int IncrementArg1(Unused, int* p, Unused) { - return ++(*p); -} - -... WillOnce(Invoke(IncrementArg1)); -``` - -There are several things unsatisfactory about this approach: - - * Even though the action only cares about the second argument of the mock function, its definition needs to list other arguments as dummies. This is tedious. - * The defined action is usable only in mock functions that takes exactly 3 arguments - an unnecessary restriction. - * To use the action, one has to say `Invoke(IncrementArg1)`, which isn't as nice as `IncrementArg1()`. - -The latter two problems can be overcome using `MakePolymorphicAction()`, -but it requires much more boilerplate code: - -```cpp -class IncrementArg1Action { - public: - template - Result Perform(const ArgumentTuple& args) const { - return ++(*tr1::get<1>(args)); - } -}; - -PolymorphicAction IncrementArg1() { - return MakePolymorphicAction(IncrementArg1Action()); -} - -... WillOnce(IncrementArg1()); -``` - -Our goal is to allow defining custom actions with the least amount of -boiler-plate C++ requires. - -## Solution ## - -We propose to introduce a new macro: -```cpp -ACTION(name) { statements; } -``` - -Using this in a namespace scope will define an action with the given -name that executes the statements. Inside the statements, you can -refer to the K-th (0-based) argument of the mock function as `argK`. -For example: -```cpp -ACTION(IncrementArg1) { return ++(*arg1); } -``` -allows you to write -```cpp -... WillOnce(IncrementArg1()); -``` - -Note that you don't need to specify the types of the mock function -arguments, as brevity is a top design goal here. Rest assured that -your code is still type-safe though: you'll get a compiler error if -`*arg1` doesn't support the `++` operator, or if the type of -`++(*arg1)` isn't compatible with the mock function's return type. - -Another example: -```cpp -ACTION(Foo) { - (*arg2)(5); - Blah(); - *arg1 = 0; - return arg0; -} -``` -defines an action `Foo()` that invokes argument #2 (a function pointer) -with 5, calls function `Blah()`, sets the value pointed to by argument -#1 to 0, and returns argument #0. - -For more convenience and flexibility, you can also use the following -pre-defined symbols in the body of `ACTION`: - -| Argument | Description | -|:----------------|:-------------------------------------------------------------| -| `argK_type` | The type of the K-th (0-based) argument of the mock function | -| `args` | All arguments of the mock function as a tuple | -| `args_type` | The type of all arguments of the mock function as a tuple | -| `return_type` | The return type of the mock function | -| `function_type` | The type of the mock function | - -For example, when using an `ACTION` as a stub action for mock function: -```cpp -int DoSomething(bool flag, int* ptr); -``` -we have: - -| **Pre-defined Symbol** | **Is Bound To** | -|:-----------------------|:----------------| -| `arg0` | the value of `flag` | -| `arg0_type` | the type `bool` | -| `arg1` | the value of `ptr` | -| `arg1_type` | the type `int*` | -| `args` | the tuple `(flag, ptr)` | -| `args_type` | the type `std::tr1::tuple` | -| `return_type` | the type `int` | -| `function_type` | the type `int(bool, int*)` | - -## Parameterized actions ## - -Sometimes you'll want to parameterize the action. For that we propose -another macro -```cpp -ACTION_P(name, param) { statements; } -``` - -For example, -```cpp -ACTION_P(Add, n) { return arg0 + n; } -``` -will allow you to write -```cpp -// Returns argument #0 + 5. -... WillOnce(Add(5)); -``` - -For convenience, we use the term _arguments_ for the values used to -invoke the mock function, and the term _parameters_ for the values -used to instantiate an action. - -Note that you don't need to provide the type of the parameter either. -Suppose the parameter is named `param`, you can also use the -Google-Mock-defined symbol `param_type` to refer to the type of the -parameter as inferred by the compiler. - -We will also provide `ACTION_P2`, `ACTION_P3`, and etc to support -multi-parameter actions. For example, -```cpp -ACTION_P2(ReturnDistanceTo, x, y) { - double dx = arg0 - x; - double dy = arg1 - y; - return sqrt(dx*dx + dy*dy); -} -``` -lets you write -```cpp -... WillOnce(ReturnDistanceTo(5.0, 26.5)); -``` - -You can view `ACTION` as a degenerated parameterized action where the -number of parameters is 0. - -## Advanced Usages ## - -### Overloading Actions ### - -You can easily define actions overloaded on the number of parameters: -```cpp -ACTION_P(Plus, a) { ... } -ACTION_P2(Plus, a, b) { ... } -``` - -### Restricting the Type of an Argument or Parameter ### - -For maximum brevity and reusability, the `ACTION*` macros don't let -you specify the types of the mock function arguments and the action -parameters. Instead, we let the compiler infer the types for us. - -Sometimes, however, we may want to be more explicit about the types. -There are several tricks to do that. For example: -```cpp -ACTION(Foo) { - // Makes sure arg0 can be converted to int. - int n = arg0; - ... use n instead of arg0 here ... -} - -ACTION_P(Bar, param) { - // Makes sure the type of arg1 is const char*. - ::testing::StaticAssertTypeEq(); - - // Makes sure param can be converted to bool. - bool flag = param; -} -``` -where `StaticAssertTypeEq` is a compile-time assertion we plan to add to -Google Test (the name is chosen to match `static_assert` in C++0x). - -### Using the ACTION Object's Type ### - -If you are writing a function that returns an `ACTION` object, you'll -need to know its type. The type depends on the macro used to define -the action and the parameter types. The rule is relatively simple: -| **Given Definition** | **Expression** | **Has Type** | -|:-------------------------|:-----------------------------|:-------------------------| -| `ACTION(Foo)` | `Foo()` | `FooAction` | -| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP` | -| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2` | -| ... | ... | ... | - -Note that we have to pick different suffixes (`Action`, `ActionP`, -`ActionP2`, and etc) for actions with different numbers of parameters, -or the action definitions cannot be overloaded on the number of -parameters. - -## When to Use ## - -While the new macros are very convenient, please also consider other -means of implementing actions (e.g. via `ActionInterface` or -`MakePolymorphicAction()`), especially if you need to use the defined -action a lot. While the other approaches require more work, they give -you more control on the types of the mock function arguments and the -action parameters, which in general leads to better compiler error -messages that pay off in the long run. They also allow overloading -actions based on parameter types, as opposed to just the number of -parameters. - -## Related Work ## - -As you may have realized, the `ACTION*` macros resemble closures (also -known as lambda expressions or anonymous functions). Indeed, both of -them seek to lower the syntactic overhead for defining a function. - -C++0x will support lambdas, but they are not part of C++ right now. -Some non-standard libraries (most notably BLL or Boost Lambda Library) -try to alleviate this problem. However, they are not a good choice -for defining actions as: - - * They are non-standard and not widely installed. Google Mock only depends on standard libraries and `tr1::tuple`, which is part of the new C++ standard and comes with gcc 4+. We want to keep it that way. - * They are not trivial to learn. - * They will become obsolete when C++0x's lambda feature is widely supported. We don't want to make our users use a dying library. - * Since they are based on operators, they are rather ad hoc: you cannot use statements, and you cannot pass the lambda arguments to a function, for example. - * They have subtle semantics that easily confuses new users. For example, in expression `_1++ + foo++`, `foo` will be incremented only once where the expression is evaluated, while `_1` will be incremented every time the unnamed function is invoked. This is far from intuitive. - -`ACTION*` avoid all these problems. - -## Future Improvements ## - -There may be a need for composing `ACTION*` definitions (i.e. invoking -another `ACTION` inside the definition of one `ACTION*`). We are not -sure we want it yet, as one can get a similar effect by putting -`ACTION` definitions in function templates and composing the function -templates. We'll revisit this based on user feedback. - -The reason we don't allow `ACTION*()` inside a function body is that -the current C++ standard doesn't allow function-local types to be used -to instantiate templates. The upcoming C++0x standard will lift this -restriction. Once this feature is widely supported by compilers, we -can revisit the implementation and add support for using `ACTION*()` -inside a function. - -C++0x will also support lambda expressions. When they become -available, we may want to support using lambdas as actions. - -# Macros for Defining Matchers # - -Once the macros for defining actions are implemented, we plan to do -the same for matchers: - -```cpp -MATCHER(name) { statements; } -``` - -where you can refer to the value being matched as `arg`. For example, -given: - -```cpp -MATCHER(IsPositive) { return arg > 0; } -``` - -you can use `IsPositive()` as a matcher that matches a value iff it is -greater than 0. - -We will also add `MATCHER_P`, `MATCHER_P2`, and etc for parameterized -matchers. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/Documentation.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/Documentation.md deleted file mode 100644 index a42bd11356c..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/Documentation.md +++ /dev/null @@ -1,15 +0,0 @@ -This page lists all documentation markdown files for Google Mock **(the -current git version)** --- **if you use a former version of Google Mock, please read the -documentation for that specific version instead (e.g. by checking out -the respective git branch/tag).** - - * [ForDummies](ForDummies.md) -- start here if you are new to Google Mock. - * [CheatSheet](CheatSheet.md) -- a quick reference. - * [CookBook](CookBook.md) -- recipes for doing various tasks using Google Mock. - * [FrequentlyAskedQuestions](FrequentlyAskedQuestions.md) -- check here before asking a question on the mailing list. - -To contribute code to Google Mock, read: - - * [CONTRIBUTING](../../CONTRIBUTING.md) -- read this _before_ writing your first patch. - * [Pump Manual](../../googletest/docs/PumpManual.md) -- how we generate some of Google Mock's source files. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/ForDummies.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/ForDummies.md deleted file mode 100644 index e2a430f8b66..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/ForDummies.md +++ /dev/null @@ -1,447 +0,0 @@ - - -(**Note:** If you get compiler errors that you don't understand, be sure to consult [Google Mock Doctor](FrequentlyAskedQuestions.md#how-am-i-supposed-to-make-sense-of-these-horrible-template-errors).) - -# What Is Google C++ Mocking Framework? # -When you write a prototype or test, often it's not feasible or wise to rely on real objects entirely. A **mock object** implements the same interface as a real object (so it can be used as one), but lets you specify at run time how it will be used and what it should do (which methods will be called? in which order? how many times? with what arguments? what will they return? etc). - -**Note:** It is easy to confuse the term _fake objects_ with mock objects. Fakes and mocks actually mean very different things in the Test-Driven Development (TDD) community: - - * **Fake** objects have working implementations, but usually take some shortcut (perhaps to make the operations less expensive), which makes them not suitable for production. An in-memory file system would be an example of a fake. - * **Mocks** are objects pre-programmed with _expectations_, which form a specification of the calls they are expected to receive. - -If all this seems too abstract for you, don't worry - the most important thing to remember is that a mock allows you to check the _interaction_ between itself and code that uses it. The difference between fakes and mocks will become much clearer once you start to use mocks. - -**Google C++ Mocking Framework** (or **Google Mock** for short) is a library (sometimes we also call it a "framework" to make it sound cool) for creating mock classes and using them. It does to C++ what [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/) do to Java. - -Using Google Mock involves three basic steps: - - 1. Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; - 1. Create some mock objects and specify its expectations and behavior using an intuitive syntax; - 1. Exercise code that uses the mock objects. Google Mock will catch any violation of the expectations as soon as it arises. - -# Why Google Mock? # -While mock objects help you remove unnecessary dependencies in tests and make them fast and reliable, using mocks manually in C++ is _hard_: - - * Someone has to implement the mocks. The job is usually tedious and error-prone. No wonder people go great distances to avoid it. - * The quality of those manually written mocks is a bit, uh, unpredictable. You may see some really polished ones, but you may also see some that were hacked up in a hurry and have all sorts of ad-hoc restrictions. - * The knowledge you gained from using one mock doesn't transfer to the next. - -In contrast, Java and Python programmers have some fine mock frameworks, which automate the creation of mocks. As a result, mocking is a proven effective technique and widely adopted practice in those communities. Having the right tool absolutely makes the difference. - -Google Mock was built to help C++ programmers. It was inspired by [jMock](http://www.jmock.org/) and [EasyMock](http://www.easymock.org/), but designed with C++'s specifics in mind. It is your friend if any of the following problems is bothering you: - - * You are stuck with a sub-optimal design and wish you had done more prototyping before it was too late, but prototyping in C++ is by no means "rapid". - * Your tests are slow as they depend on too many libraries or use expensive resources (e.g. a database). - * Your tests are brittle as some resources they use are unreliable (e.g. the network). - * You want to test how your code handles a failure (e.g. a file checksum error), but it's not easy to cause one. - * You need to make sure that your module interacts with other modules in the right way, but it's hard to observe the interaction; therefore you resort to observing the side effects at the end of the action, which is awkward at best. - * You want to "mock out" your dependencies, except that they don't have mock implementations yet; and, frankly, you aren't thrilled by some of those hand-written mocks. - -We encourage you to use Google Mock as: - - * a _design_ tool, for it lets you experiment with your interface design early and often. More iterations lead to better designs! - * a _testing_ tool to cut your tests' outbound dependencies and probe the interaction between your module and its collaborators. - -# Getting Started # -Using Google Mock is easy! Inside your C++ source file, just `#include` `"gtest/gtest.h"` and `"gmock/gmock.h"`, and you are ready to go. - -# A Case for Mock Turtles # -Let's look at an example. Suppose you are developing a graphics program that relies on a LOGO-like API for drawing. How would you test that it does the right thing? Well, you can run it and compare the screen with a golden screen snapshot, but let's admit it: tests like this are expensive to run and fragile (What if you just upgraded to a shiny new graphics card that has better anti-aliasing? Suddenly you have to update all your golden images.). It would be too painful if all your tests are like this. Fortunately, you learned about Dependency Injection and know the right thing to do: instead of having your application talk to the drawing API directly, wrap the API in an interface (say, `Turtle`) and code to that interface: - -```cpp -class Turtle { - ... - virtual ~Turtle() {} - virtual void PenUp() = 0; - virtual void PenDown() = 0; - virtual void Forward(int distance) = 0; - virtual void Turn(int degrees) = 0; - virtual void GoTo(int x, int y) = 0; - virtual int GetX() const = 0; - virtual int GetY() const = 0; -}; -``` - -(Note that the destructor of `Turtle` **must** be virtual, as is the case for **all** classes you intend to inherit from - otherwise the destructor of the derived class will not be called when you delete an object through a base pointer, and you'll get corrupted program states like memory leaks.) - -You can control whether the turtle's movement will leave a trace using `PenUp()` and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and `GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the turtle. - -Your program will normally use a real implementation of this interface. In tests, you can use a mock implementation instead. This allows you to easily check what drawing primitives your program is calling, with what arguments, and in which order. Tests written this way are much more robust (they won't break because your new machine does anti-aliasing differently), easier to read and maintain (the intent of a test is expressed in the code, not in some binary images), and run _much, much faster_. - -# Writing the Mock Class # -If you are lucky, the mocks you need to use have already been implemented by some nice people. If, however, you find yourself in the position to write a mock class, relax - Google Mock turns this task into a fun game! (Well, almost.) - -## How to Define It ## -Using the `Turtle` interface as example, here are the simple steps you need to follow: - - 1. Derive a class `MockTurtle` from `Turtle`. - 1. Take a _virtual_ function of `Turtle` (while it's possible to [mock non-virtual methods using templates](CookBook.md#mocking-nonvirtual-methods), it's much more involved). Count how many arguments it has. - 1. In the `public:` section of the child class, write `MOCK_METHODn();` (or `MOCK_CONST_METHODn();` if you are mocking a `const` method), where `n` is the number of the arguments; if you counted wrong, shame on you, and a compiler error will tell you so. - 1. Now comes the fun part: you take the function signature, cut-and-paste the _function name_ as the _first_ argument to the macro, and leave what's left as the _second_ argument (in case you're curious, this is the _type of the function_). - 1. Repeat until all virtual functions you want to mock are done. - -After the process, you should have something like: - -```cpp -#include "gmock/gmock.h" // Brings in Google Mock. -class MockTurtle : public Turtle { - public: - ... - MOCK_METHOD0(PenUp, void()); - MOCK_METHOD0(PenDown, void()); - MOCK_METHOD1(Forward, void(int distance)); - MOCK_METHOD1(Turn, void(int degrees)); - MOCK_METHOD2(GoTo, void(int x, int y)); - MOCK_CONST_METHOD0(GetX, int()); - MOCK_CONST_METHOD0(GetY, int()); -}; -``` - -You don't need to define these mock methods somewhere else - the `MOCK_METHOD*` macros will generate the definitions for you. It's that simple! Once you get the hang of it, you can pump out mock classes faster than your source-control system can handle your check-ins. - -**Tip:** If even this is too much work for you, you'll find the -`gmock_gen.py` tool in Google Mock's `scripts/generator/` directory (courtesy of the [cppclean](http://code.google.com/p/cppclean/) project) useful. This command-line -tool requires that you have Python 2.4 installed. You give it a C++ file and the name of an abstract class defined in it, -and it will print the definition of the mock class for you. Due to the -complexity of the C++ language, this script may not always work, but -it can be quite handy when it does. For more details, read the [user documentation](../scripts/generator/README). - -## Where to Put It ## -When you define a mock class, you need to decide where to put its definition. Some people put it in a `*_test.cc`. This is fine when the interface being mocked (say, `Foo`) is owned by the same person or team. Otherwise, when the owner of `Foo` changes it, your test could break. (You can't really expect `Foo`'s maintainer to fix every test that uses `Foo`, can you?) - -So, the rule of thumb is: if you need to mock `Foo` and it's owned by others, define the mock class in `Foo`'s package (better, in a `testing` sub-package such that you can clearly separate production code and testing utilities), and put it in a `mock_foo.h`. Then everyone can reference `mock_foo.h` from their tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and only tests that depend on the changed methods need to be fixed. - -Another way to do it: you can introduce a thin layer `FooAdaptor` on top of `Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb changes in `Foo` much more easily. While this is more work initially, carefully choosing the adaptor interface can make your code easier to write and more readable (a net win in the long run), as you can choose `FooAdaptor` to fit your specific domain much better than `Foo` does. - -# Using Mocks in Tests # -Once you have a mock class, using it is easy. The typical work flow is: - - 1. Import the Google Mock names from the `testing` namespace such that you can use them unqualified (You only have to do it once per file. Remember that namespaces are a good idea and good for your health.). - 1. Create some mock objects. - 1. Specify your expectations on them (How many times will a method be called? With what arguments? What should it do? etc.). - 1. Exercise some code that uses the mocks; optionally, check the result using Google Test assertions. If a mock method is called more than expected or with wrong arguments, you'll get an error immediately. - 1. When a mock is destructed, Google Mock will automatically check whether all expectations on it have been satisfied. - -Here's an example: - -```cpp -#include "path/to/mock-turtle.h" -#include "gmock/gmock.h" -#include "gtest/gtest.h" -using ::testing::AtLeast; // #1 - -TEST(PainterTest, CanDrawSomething) { - MockTurtle turtle; // #2 - EXPECT_CALL(turtle, PenDown()) // #3 - .Times(AtLeast(1)); - - Painter painter(&turtle); // #4 - - EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); -} // #5 - -int main(int argc, char** argv) { - // The following line must be executed to initialize Google Mock - // (and Google Test) before running the tests. - ::testing::InitGoogleMock(&argc, argv); - return RUN_ALL_TESTS(); -} -``` - -As you might have guessed, this test checks that `PenDown()` is called at least once. If the `painter` object didn't call this method, your test will fail with a message like this: - -``` -path/to/my_test.cc:119: Failure -Actual function call count doesn't match this expectation: -Actually: never called; -Expected: called at least once. -``` - -**Tip 1:** If you run the test from an Emacs buffer, you can hit `` on the line number displayed in the error message to jump right to the failed expectation. - -**Tip 2:** If your mock objects are never deleted, the final verification won't happen. Therefore it's a good idea to use a heap leak checker in your tests when you allocate mocks on the heap. - -**Important note:** Google Mock requires expectations to be set **before** the mock functions are called, otherwise the behavior is **undefined**. In particular, you mustn't interleave `EXPECT_CALL()`s and calls to the mock functions. - -This means `EXPECT_CALL()` should be read as expecting that a call will occur _in the future_, not that a call has occurred. Why does Google Mock work like that? Well, specifying the expectation beforehand allows Google Mock to report a violation as soon as it arises, when the context (stack trace, etc) is still available. This makes debugging much easier. - -Admittedly, this test is contrived and doesn't do much. You can easily achieve the same effect without using Google Mock. However, as we shall reveal soon, Google Mock allows you to do _much more_ with the mocks. - -## Using Google Mock with Any Testing Framework ## -If you want to use something other than Google Test (e.g. [CppUnit](http://sourceforge.net/projects/cppunit/) or -[CxxTest](https://cxxtest.com/)) as your testing framework, just change the `main()` function in the previous section to: -```cpp -int main(int argc, char** argv) { - // The following line causes Google Mock to throw an exception on failure, - // which will be interpreted by your testing framework as a test failure. - ::testing::GTEST_FLAG(throw_on_failure) = true; - ::testing::InitGoogleMock(&argc, argv); - ... whatever your testing framework requires ... -} -``` - -This approach has a catch: it makes Google Mock throw an exception -from a mock object's destructor sometimes. With some compilers, this -sometimes causes the test program to crash. You'll still be able to -notice that the test has failed, but it's not a graceful failure. - -A better solution is to use Google Test's -[event listener API](../../googletest/docs/advanced.md#extending-googletest-by-handling-test-events) -to report a test failure to your testing framework properly. You'll need to -implement the `OnTestPartResult()` method of the event listener interface, but it -should be straightforward. - -If this turns out to be too much work, we suggest that you stick with -Google Test, which works with Google Mock seamlessly (in fact, it is -technically part of Google Mock.). If there is a reason that you -cannot use Google Test, please let us know. - -# Setting Expectations # -The key to using a mock object successfully is to set the _right expectations_ on it. If you set the expectations too strict, your test will fail as the result of unrelated changes. If you set them too loose, bugs can slip through. You want to do it just right such that your test can catch exactly the kind of bugs you intend it to catch. Google Mock provides the necessary means for you to do it "just right." - -## General Syntax ## -In Google Mock we use the `EXPECT_CALL()` macro to set an expectation on a mock method. The general syntax is: - -```cpp -EXPECT_CALL(mock_object, method(matchers)) - .Times(cardinality) - .WillOnce(action) - .WillRepeatedly(action); -``` - -The macro has two arguments: first the mock object, and then the method and its arguments. Note that the two are separated by a comma (`,`), not a period (`.`). (Why using a comma? The answer is that it was necessary for technical reasons.) - -The macro can be followed by some optional _clauses_ that provide more information about the expectation. We'll discuss how each clause works in the coming sections. - -This syntax is designed to make an expectation read like English. For example, you can probably guess that - -```cpp -using ::testing::Return; -... -EXPECT_CALL(turtle, GetX()) - .Times(5) - .WillOnce(Return(100)) - .WillOnce(Return(150)) - .WillRepeatedly(Return(200)); -``` - -says that the `turtle` object's `GetX()` method will be called five times, it will return 100 the first time, 150 the second time, and then 200 every time. Some people like to call this style of syntax a Domain-Specific Language (DSL). - -**Note:** Why do we use a macro to do this? It serves two purposes: first it makes expectations easily identifiable (either by `grep` or by a human reader), and second it allows Google Mock to include the source file location of a failed expectation in messages, making debugging easier. - -## Matchers: What Arguments Do We Expect? ## -When a mock function takes arguments, we must specify what arguments we are expecting; for example: - -```cpp -// Expects the turtle to move forward by 100 units. -EXPECT_CALL(turtle, Forward(100)); -``` - -Sometimes you may not want to be too specific (Remember that talk about tests being too rigid? Over specification leads to brittle tests and obscures the intent of tests. Therefore we encourage you to specify only what's necessary - no more, no less.). If you care to check that `Forward()` will be called but aren't interested in its actual argument, write `_` as the argument, which means "anything goes": - -```cpp -using ::testing::_; -... -// Expects the turtle to move forward. -EXPECT_CALL(turtle, Forward(_)); -``` - -`_` is an instance of what we call **matchers**. A matcher is like a predicate and can test whether an argument is what we'd expect. You can use a matcher inside `EXPECT_CALL()` wherever a function argument is expected. - -A list of built-in matchers can be found in the [CheatSheet](CheatSheet.md). For example, here's the `Ge` (greater than or equal) matcher: - -```cpp -using ::testing::Ge; -... -EXPECT_CALL(turtle, Forward(Ge(100))); -``` - -This checks that the turtle will be told to go forward by at least 100 units. - -## Cardinalities: How Many Times Will It Be Called? ## -The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We call its argument a **cardinality** as it tells _how many times_ the call should occur. It allows us to repeat an expectation many times without actually writing it as many times. More importantly, a cardinality can be "fuzzy", just like a matcher can be. This allows a user to express the intent of a test exactly. - -An interesting special case is when we say `Times(0)`. You may have guessed - it means that the function shouldn't be called with the given arguments at all, and Google Mock will report a Google Test failure whenever the function is (wrongfully) called. - -We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the list of built-in cardinalities you can use, see the [CheatSheet](CheatSheet.md). - -The `Times()` clause can be omitted. **If you omit `Times()`, Google Mock will infer the cardinality for you.** The rules are easy to remember: - - * If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. - * If there are `n WillOnce()`'s but **no** `WillRepeatedly()`, where `n` >= 1, the cardinality is `Times(n)`. - * If there are `n WillOnce()`'s and **one** `WillRepeatedly()`, where `n` >= 0, the cardinality is `Times(AtLeast(n))`. - -**Quick quiz:** what do you think will happen if a function is expected to be called twice but actually called four times? - -## Actions: What Should It Do? ## -Remember that a mock object doesn't really have a working implementation? We as users have to tell it what to do when a method is invoked. This is easy in Google Mock. - -First, if the return type of a mock function is a built-in type or a pointer, the function has a **default action** (a `void` function will just return, a `bool` function will return `false`, and other functions will return 0). In addition, in C++ 11 and above, a mock function whose return type is default-constructible (i.e. has a default constructor) has a default action of returning a default-constructed value. If you don't say anything, this behavior will be used. - -Second, if a mock function doesn't have a default action, or the default action doesn't suit you, you can specify the action to be taken each time the expectation matches using a series of `WillOnce()` clauses followed by an optional `WillRepeatedly()`. For example, - -```cpp -using ::testing::Return; -... -EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillOnce(Return(300)); -``` - -This says that `turtle.GetX()` will be called _exactly three times_ (Google Mock inferred this from how many `WillOnce()` clauses we've written, since we didn't explicitly write `Times()`), and will return 100, 200, and 300 respectively. - -```cpp -using ::testing::Return; -... -EXPECT_CALL(turtle, GetY()) - .WillOnce(Return(100)) - .WillOnce(Return(200)) - .WillRepeatedly(Return(300)); -``` - -says that `turtle.GetY()` will be called _at least twice_ (Google Mock knows this as we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no explicit `Times()`), will return 100 the first time, 200 the second time, and 300 from the third time on. - -Of course, if you explicitly write a `Times()`, Google Mock will not try to infer the cardinality itself. What if the number you specified is larger than there are `WillOnce()` clauses? Well, after all `WillOnce()`s are used up, Google Mock will do the _default_ action for the function every time (unless, of course, you have a `WillRepeatedly()`.). - -What can we do inside `WillOnce()` besides `Return()`? You can return a reference using `ReturnRef(variable)`, or invoke a pre-defined function, among [others](CheatSheet.md#actions). - -**Important note:** The `EXPECT_CALL()` statement evaluates the action clause only once, even though the action may be performed many times. Therefore you must be careful about side effects. The following may not do what you want: - -```cpp -int n = 100; -EXPECT_CALL(turtle, GetX()) -.Times(4) -.WillRepeatedly(Return(n++)); -``` - -Instead of returning 100, 101, 102, ..., consecutively, this mock function will always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will return the same pointer every time. If you want the side effect to happen every time, you need to define a custom action, which we'll teach in the [CookBook](CookBook.md). - -Time for another quiz! What do you think the following means? - -```cpp -using ::testing::Return; -... -EXPECT_CALL(turtle, GetY()) -.Times(4) -.WillOnce(Return(100)); -``` - -Obviously `turtle.GetY()` is expected to be called four times. But if you think it will return 100 every time, think twice! Remember that one `WillOnce()` clause will be consumed each time the function is invoked and the default action will be taken afterwards. So the right answer is that `turtle.GetY()` will return 100 the first time, but **return 0 from the second time on**, as returning 0 is the default action for `int` functions. - -## Using Multiple Expectations ## -So far we've only shown examples where you have a single expectation. More realistically, you're going to specify expectations on multiple mock methods, which may be from multiple mock objects. - -By default, when a mock method is invoked, Google Mock will search the expectations in the **reverse order** they are defined, and stop when an active expectation that matches the arguments is found (you can think of it as "newer rules override older ones."). If the matching expectation cannot take any more calls, you will get an upper-bound-violated failure. Here's an example: - -```cpp -using ::testing::_; -... -EXPECT_CALL(turtle, Forward(_)); // #1 -EXPECT_CALL(turtle, Forward(10)) // #2 - .Times(2); -``` - -If `Forward(10)` is called three times in a row, the third time it will be an error, as the last matching expectation (#2) has been saturated. If, however, the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, as now #1 will be the matching expectation. - -**Side note:** Why does Google Mock search for a match in the _reverse_ order of the expectations? The reason is that this allows a user to set up the default expectations in a mock object's constructor or the test fixture's set-up phase and then customize the mock by writing more specific expectations in the test body. So, if you have two expectations on the same method, you want to put the one with more specific matchers **after** the other, or the more specific rule would be shadowed by the more general one that comes after it. - -## Ordered vs Unordered Calls ## -By default, an expectation can match a call even though an earlier expectation hasn't been satisfied. In other words, the calls don't have to occur in the order the expectations are specified. - -Sometimes, you may want all the expected calls to occur in a strict order. To say this in Google Mock is easy: - -```cpp -using ::testing::InSequence; -... -TEST(FooTest, DrawsLineSegment) { - ... - { - InSequence dummy; - - EXPECT_CALL(turtle, PenDown()); - EXPECT_CALL(turtle, Forward(100)); - EXPECT_CALL(turtle, PenUp()); - } - Foo(); -} -``` - -By creating an object of type `InSequence`, all expectations in its scope are put into a _sequence_ and have to occur _sequentially_. Since we are just relying on the constructor and destructor of this object to do the actual work, its name is really irrelevant. - -In this example, we test that `Foo()` calls the three expected functions in the order as written. If a call is made out-of-order, it will be an error. - -(What if you care about the relative order of some of the calls, but not all of them? Can you specify an arbitrary partial order? The answer is ... yes! If you are impatient, the details can be found in the [CookBook](CookBook.md#expecting-partially-ordered-calls).) - -## All Expectations Are Sticky (Unless Said Otherwise) ## -Now let's do a quick quiz to see how well you can use this mock stuff already. How would you test that the turtle is asked to go to the origin _exactly twice_ (you want to ignore any other instructions it receives)? - -After you've come up with your answer, take a look at ours and compare notes (solve it yourself first - don't cheat!): - -```cpp -using ::testing::_; -... -EXPECT_CALL(turtle, GoTo(_, _)) // #1 - .Times(AnyNumber()); -EXPECT_CALL(turtle, GoTo(0, 0)) // #2 - .Times(2); -``` - -Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, Google Mock will see that the arguments match expectation #2 (remember that we always pick the last matching expectation). Now, since we said that there should be only two such calls, Google Mock will report an error immediately. This is basically what we've told you in the "Using Multiple Expectations" section above. - -This example shows that **expectations in Google Mock are "sticky" by default**, in the sense that they remain active even after we have reached their invocation upper bounds. This is an important rule to remember, as it affects the meaning of the spec, and is **different** to how it's done in many other mocking frameworks (Why'd we do that? Because we think our rule makes the common cases easier to express and understand.). - -Simple? Let's see if you've really understood it: what does the following code say? - -```cpp -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)); -} -``` - -If you think it says that `turtle.GetX()` will be called `n` times and will return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we said, expectations are sticky. So, the second time `turtle.GetX()` is called, the last (latest) `EXPECT_CALL()` statement will match, and will immediately lead to an "upper bound exceeded" error - this piece of code is not very useful! - -One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is to explicitly say that the expectations are _not_ sticky. In other words, they should _retire_ as soon as they are saturated: - -```cpp -using ::testing::Return; -... -for (int i = n; i > 0; i--) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); -} -``` - -And, there's a better way to do it: in this case, we expect the calls to occur in a specific order, and we line up the actions to match the order. Since the order is important here, we should make it explicit using a sequence: - -```cpp -using ::testing::InSequence; -using ::testing::Return; -... -{ - InSequence s; - - for (int i = 1; i <= n; i++) { - EXPECT_CALL(turtle, GetX()) - .WillOnce(Return(10*i)) - .RetiresOnSaturation(); - } -} -``` - -By the way, the other situation where an expectation may _not_ be sticky is when it's in a sequence - as soon as another expectation that comes after it in the sequence has been used, it automatically retires (and will never be used to match any call). - -## Uninteresting Calls ## -A mock object may have many methods, and not all of them are that interesting. For example, in some tests we may not care about how many times `GetX()` and `GetY()` get called. - -In Google Mock, if you are not interested in a method, just don't say anything about it. If a call to this method occurs, you'll see a warning in the test output, but it won't be a failure. - -# What Now? # -Congratulations! You've learned enough about Google Mock to start using it. Now, you might want to join the [googlemock](http://groups.google.com/group/googlemock) discussion group and actually write some tests using Google Mock - it will be fun. Hey, it may even be addictive - you've been warned. - -Then, if you feel like increasing your mock quotient, you should move on to the [CookBook](CookBook.md). You can learn many advanced features of Google Mock there -- and advance your level of enjoyment and testing bliss. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/FrequentlyAskedQuestions.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/FrequentlyAskedQuestions.md deleted file mode 100644 index e91f038c053..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/FrequentlyAskedQuestions.md +++ /dev/null @@ -1,627 +0,0 @@ - - -Please send your questions to the -[googlemock](http://groups.google.com/group/googlemock) discussion -group. If you need help with compiler errors, make sure you have -tried [Google Mock Doctor](#how-am-i-supposed-to-make-sense-of-these-horrible-template-errors) first. - -## When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? ## - -In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](CookBook.md#mocking-nonvirtual-methods). - -## I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? ## - -After version 1.4.0 of Google Mock was released, we had an idea on how -to make it easier to write matchers that can generate informative -messages efficiently. We experimented with this idea and liked what -we saw. Therefore we decided to implement it. - -Unfortunately, this means that if you have defined your own matchers -by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`, -your definitions will no longer compile. Matchers defined using the -`MATCHER*` family of macros are not affected. - -Sorry for the hassle if your matchers are affected. We believe it's -in everyone's long-term interest to make this change sooner than -later. Fortunately, it's usually not hard to migrate an existing -matcher to the new API. Here's what you need to do: - -If you wrote your matcher like this: -```cpp -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` - -you'll need to change it to: -```cpp -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - ... -}; -``` -(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second -argument of type `MatchResultListener*`.) - -If you were also using `ExplainMatchResultTo()` to improve the matcher -message: -```cpp -// Old matcher definition that doesn't work with the lastest -// Google Mock. -using ::testing::MatcherInterface; -... -class MyWonderfulMatcher : public MatcherInterface { - public: - ... - virtual bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetFoo() > 5; - } - - virtual void ExplainMatchResultTo(MyType value, - ::std::ostream* os) const { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Foo property is " << value.GetFoo(); - } - ... -}; -``` - -you should move the logic of `ExplainMatchResultTo()` into -`MatchAndExplain()`, using the `MatchResultListener` argument where -the `::std::ostream` was used: -```cpp -// New matcher definition that works with the latest Google Mock. -using ::testing::MatcherInterface; -using ::testing::MatchResultListener; -... -class MyWonderfulMatcher : public MatcherInterface { - public: - ... - virtual bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Foo property is " << value.GetFoo(); - return value.GetFoo() > 5; - } - ... -}; -``` - -If your matcher is defined using `MakePolymorphicMatcher()`: -```cpp -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you should rename the `Matches()` method to `MatchAndExplain()` and -add a `MatchResultListener*` argument (the same as what you need to do -for matchers defined by implementing `MatcherInterface`): -```cpp -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -If your polymorphic matcher uses `ExplainMatchResultTo()` for better -failure messages: -```cpp -// Old matcher definition that doesn't work with the latest -// Google Mock. -using ::testing::MakePolymorphicMatcher; -... -class MyGreatMatcher { - public: - ... - bool Matches(MyType value) const { - // Returns true if value matches. - return value.GetBar() < 42; - } - ... -}; -void ExplainMatchResultTo(const MyGreatMatcher& matcher, - MyType value, - ::std::ostream* os) { - // Prints some helpful information to os to help - // a user understand why value matches (or doesn't match). - *os << "the Bar property is " << value.GetBar(); -} -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -you'll need to move the logic inside `ExplainMatchResultTo()` to -`MatchAndExplain()`: -```cpp -// New matcher definition that works with the latest Google Mock. -using ::testing::MakePolymorphicMatcher; -using ::testing::MatchResultListener; -... -class MyGreatMatcher { - public: - ... - bool MatchAndExplain(MyType value, - MatchResultListener* listener) const { - // Returns true if value matches. - *listener << "the Bar property is " << value.GetBar(); - return value.GetBar() < 42; - } - ... -}; -... MakePolymorphicMatcher(MyGreatMatcher()) ... -``` - -For more information, you can read these -[two](CookBook.md#writing-new-monomorphic-matchers) -[recipes](CookBook.md#writing-new-polymorphic-matchers) -from the cookbook. As always, you -are welcome to post questions on `googlemock@googlegroups.com` if you -need any help. - -## When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. ## - -Google Mock works out of the box with Google Test. However, it's easy -to configure it to work with any testing framework of your choice. -[Here](ForDummies.md#using-google-mock-with-any-testing-framework) is how. - -## How am I supposed to make sense of these horrible template errors? ## - -If you are confused by the compiler errors gcc threw at you, -try consulting the _Google Mock Doctor_ tool first. What it does is to -scan stdin for gcc error messages, and spit out diagnoses on the -problems (we call them diseases) your code has. - -To "install", run command: -``` -alias gmd='/scripts/gmock_doctor.py' -``` - -To use it, do: -``` - 2>&1 | gmd -``` - -For example: -``` -make my_test 2>&1 | gmd -``` - -Or you can run `gmd` and copy-n-paste gcc's error messages to it. - -## Can I mock a variadic function? ## - -You cannot mock a variadic function (i.e. a function taking ellipsis -(`...`) arguments) directly in Google Mock. - -The problem is that in general, there is _no way_ for a mock object to -know how many arguments are passed to the variadic method, and what -the arguments' types are. Only the _author of the base class_ knows -the protocol, and we cannot look into their head. - -Therefore, to mock such a function, the _user_ must teach the mock -object how to figure out the number of arguments and their types. One -way to do it is to provide overloaded versions of the function. - -Ellipsis arguments are inherited from C and not really a C++ feature. -They are unsafe to use and don't work with arguments that have -constructors or destructors. Therefore we recommend to avoid them in -C++ as much as possible. - -## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? ## - -If you compile this using Microsoft Visual C++ 2005 SP1: -```cpp -class Foo { - ... - virtual void Bar(const int i) = 0; -}; - -class MockFoo : public Foo { - ... - MOCK_METHOD1(Bar, void(const int i)); -}; -``` -You may get the following warning: -``` -warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier -``` - -This is a MSVC bug. The same code compiles fine with gcc ,for -example. If you use Visual C++ 2008 SP1, you would get the warning: -``` -warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers -``` - -In C++, if you _declare_ a function with a `const` parameter, the -`const` modifier is _ignored_. Therefore, the `Foo` base class above -is equivalent to: -```cpp -class Foo { - ... - virtual void Bar(int i) = 0; // int or const int? Makes no difference. -}; -``` - -In fact, you can _declare_ Bar() with an `int` parameter, and _define_ -it with a `const int` parameter. The compiler will still match them -up. - -Since making a parameter `const` is meaningless in the method -_declaration_, we recommend to remove it in both `Foo` and `MockFoo`. -That should workaround the VC bug. - -Note that we are talking about the _top-level_ `const` modifier here. -If the function parameter is passed by pointer or reference, declaring -the _pointee_ or _referee_ as `const` is still meaningful. For -example, the following two declarations are _not_ equivalent: -```cpp -void Bar(int* p); // Neither p nor *p is const. -void Bar(const int* p); // p is not const, but *p is. -``` - -## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? ## - -We've noticed that when the `/clr` compiler flag is used, Visual C++ -uses 5~6 times as much memory when compiling a mock class. We suggest -to avoid `/clr` when compiling native C++ mocks. - -## I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? ## - -You might want to run your test with -`--gmock_verbose=info`. This flag lets Google Mock print a trace -of every mock function call it receives. By studying the trace, -you'll gain insights on why the expectations you set are not met. - -## How can I assert that a function is NEVER called? ## - -```cpp -EXPECT_CALL(foo, Bar(_)) - .Times(0); -``` - -## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? ## - -When Google Mock detects a failure, it prints relevant information -(the mock function arguments, the state of relevant expectations, and -etc) to help the user debug. If another failure is detected, Google -Mock will do the same, including printing the state of relevant -expectations. - -Sometimes an expectation's state didn't change between two failures, -and you'll see the same description of the state twice. They are -however _not_ redundant, as they refer to _different points in time_. -The fact they are the same _is_ interesting information. - -## I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? ## - -Does the class (hopefully a pure interface) you are mocking have a -virtual destructor? - -Whenever you derive from a base class, make sure its destructor is -virtual. Otherwise Bad Things will happen. Consider the following -code: - -```cpp -class Base { - public: - // Not virtual, but should be. - ~Base() { ... } - ... -}; - -class Derived : public Base { - public: - ... - private: - std::string value_; -}; - -... - Base* p = new Derived; - ... - delete p; // Surprise! ~Base() will be called, but ~Derived() will not - // - value_ is leaked. -``` - -By changing `~Base()` to virtual, `~Derived()` will be correctly -called when `delete p` is executed, and the heap checker -will be happy. - -## The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? ## - -When people complain about this, often they are referring to code like: - -```cpp -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. However, I have to write the expectations in the -// reverse order. This sucks big time!!! -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); -``` - -The problem is that they didn't pick the **best** way to express the test's -intent. - -By default, expectations don't have to be matched in _any_ particular -order. If you want them to match in a certain order, you need to be -explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's -easy to accidentally over-specify your tests, and we want to make it -harder to do so. - -There are two better ways to write the test spec. You could either -put the expectations in sequence: - -```cpp -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. Using a sequence, we can write the expectations -// in their natural order. -{ - InSequence s; - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .RetiresOnSaturation(); - EXPECT_CALL(foo, Bar()) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -} -``` - -or you can put the sequence of actions in the same expectation: - -```cpp -// foo.Bar() should be called twice, return 1 the first time, and return -// 2 the second time. -EXPECT_CALL(foo, Bar()) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .RetiresOnSaturation(); -``` - -Back to the original questions: why does Google Mock search the -expectations (and `ON_CALL`s) from back to front? Because this -allows a user to set up a mock's behavior for the common case early -(e.g. in the mock's constructor or the test fixture's set-up phase) -and customize it with more specific rules later. If Google Mock -searches from front to back, this very useful pattern won't be -possible. - -## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL. Would it be reasonable not to show the warning in this case? ## - -When choosing between being neat and being safe, we lean toward the -latter. So the answer is that we think it's better to show the -warning. - -Often people write `ON_CALL`s in the mock object's -constructor or `SetUp()`, as the default behavior rarely changes from -test to test. Then in the test body they set the expectations, which -are often different for each test. Having an `ON_CALL` in the set-up -part of a test doesn't mean that the calls are expected. If there's -no `EXPECT_CALL` and the method is called, it's possibly an error. If -we quietly let the call go through without notifying the user, bugs -may creep in unnoticed. - -If, however, you are sure that the calls are OK, you can write - -```cpp -EXPECT_CALL(foo, Bar(_)) - .WillRepeatedly(...); -``` - -instead of - -```cpp -ON_CALL(foo, Bar(_)) - .WillByDefault(...); -``` - -This tells Google Mock that you do expect the calls and no warning should be -printed. - -Also, you can control the verbosity using the `--gmock_verbose` flag. -If you find the output too noisy when debugging, just choose a less -verbose level. - -## How can I delete the mock function's argument in an action? ## - -If you find yourself needing to perform some action that's not -supported by Google Mock directly, remember that you can define your own -actions using -[MakeAction()](CookBook.md#writing-new-actions-quickly) or -[MakePolymorphicAction()](CookBook.md#writing-new-polymorphic-actions), -or you can write a stub function and invoke it using -[Invoke()](CookBook.md#using-functionsmethodsfunctors-as-actions). - -## MOCK\_METHODn()'s second argument looks funny. Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ## - -What?! I think it's beautiful. :-) - -While which syntax looks more natural is a subjective matter to some -extent, Google Mock's syntax was chosen for several practical advantages it -has. - -Try to mock a function that takes a map as an argument: -```cpp -virtual int GetSize(const map& m); -``` - -Using the proposed syntax, it would be: -```cpp -MOCK_METHOD1(GetSize, int, const map& m); -``` - -Guess what? You'll get a compiler error as the compiler thinks that -`const map& m` are **two**, not one, arguments. To work -around this you can use `typedef` to give the map type a name, but -that gets in the way of your work. Google Mock's syntax avoids this -problem as the function's argument types are protected inside a pair -of parentheses: -```cpp -// This compiles fine. -MOCK_METHOD1(GetSize, int(const map& m)); -``` - -You still need a `typedef` if the return type contains an unprotected -comma, but that's much rarer. - -Other advantages include: - 1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax. - 1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively. Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it. - 1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in `MOCK_METHOD*`! - -## My code calls a static/global function. Can I mock it? ## - -You can, but you need to make some changes. - -In general, if you find yourself needing to mock a static function, -it's a sign that your modules are too tightly coupled (and less -flexible, less reusable, less testable, etc). You are probably better -off defining a small interface and call the function through that -interface, which then can be easily mocked. It's a bit of work -initially, but usually pays for itself quickly. - -This Google Testing Blog -[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) -says it excellently. Check it out. - -## My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! ## - -I know it's not a question, but you get an answer for free any way. :-) - -With Google Mock, you can create mocks in C++ easily. And people might be -tempted to use them everywhere. Sometimes they work great, and -sometimes you may find them, well, a pain to use. So, what's wrong in -the latter case? - -When you write a test without using mocks, you exercise the code and -assert that it returns the correct value or that the system is in an -expected state. This is sometimes called "state-based testing". - -Mocks are great for what some call "interaction-based" testing: -instead of checking the system state at the very end, mock objects -verify that they are invoked the right way and report an error as soon -as it arises, giving you a handle on the precise context in which the -error was triggered. This is often more effective and economical to -do than state-based testing. - -If you are doing state-based testing and using a test double just to -simulate the real object, you are probably better off using a fake. -Using a mock in this case causes pain, as it's not a strong point for -mocks to perform complex actions. If you experience this and think -that mocks suck, you are just not using the right tool for your -problem. Or, you might be trying to solve the wrong problem. :-) - -## I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? ## - -By all means, NO! It's just an FYI. - -What it means is that you have a mock function, you haven't set any -expectations on it (by Google Mock's rule this means that you are not -interested in calls to this function and therefore it can be called -any number of times), and it is called. That's OK - you didn't say -it's not OK to call the function! - -What if you actually meant to disallow this function to be called, but -forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`? While -one can argue that it's the user's fault, Google Mock tries to be nice and -prints you a note. - -So, when you see the message and believe that there shouldn't be any -uninteresting calls, you should investigate what's going on. To make -your life easier, Google Mock prints the function name and arguments -when an uninteresting call is encountered. - -## I want to define a custom action. Should I use Invoke() or implement the action interface? ## - -Either way is fine - you want to choose the one that's more convenient -for your circumstance. - -Usually, if your action is for a particular function type, defining it -using `Invoke()` should be easier; if your action can be used in -functions of different types (e.g. if you are defining -`Return(value)`), `MakePolymorphicAction()` is -easiest. Sometimes you want precise control on what types of -functions the action can be used in, and implementing -`ActionInterface` is the way to go here. See the implementation of -`Return()` in `include/gmock/gmock-actions.h` for an example. - -## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? ## - -You got this error as Google Mock has no idea what value it should return -when the mock method is called. `SetArgPointee()` says what the -side effect is, but doesn't say what the return value should be. You -need `DoAll()` to chain a `SetArgPointee()` with a `Return()`. - -See this [recipe](CookBook.md#mocking-side-effects) for more details and an example. - - -## My question is not in your FAQ! ## - -If you cannot find the answer to your question in this FAQ, there are -some other resources you can use: - - 1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics), - 1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.). - -Please note that creating an issue in the -[issue tracker](https://github.com/google/googletest/issues) is _not_ -a good way to get your answer, as it is monitored infrequently by a -very small number of people. - -When asking a question, it's helpful to provide as much of the -following information as possible (people cannot help you if there's -not enough information in your question): - - * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version), - * your operating system, - * the name and version of your compiler, - * the complete command line flags you give to your compiler, - * the complete compiler error messages (if the question is about compilation), - * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter. diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/KnownIssues.md b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/KnownIssues.md deleted file mode 100644 index adadf5144b1..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/docs/KnownIssues.md +++ /dev/null @@ -1,19 +0,0 @@ -As any non-trivial software system, Google Mock has some known limitations and problems. We are working on improving it, and welcome your help! The follow is a list of issues we know about. - - - -## README contains outdated information on Google Mock's compatibility with other testing frameworks ## - -The `README` file in release 1.1.0 still says that Google Mock only works with Google Test. Actually, you can configure Google Mock to work with any testing framework you choose. - -## Tests failing on machines using Power PC CPUs (e.g. some Macs) ## - -`gmock_output_test` and `gmock-printers_test` are known to fail with Power PC CPUs. This is due to portability issues with these tests, and is not an indication of problems in Google Mock itself. You can safely ignore them. - -## Failed to resolve libgtest.so.0 in tests when built against installed Google Test ## - -This only applies if you manually built and installed Google Test, and then built a Google Mock against it (either explicitly, or because gtest-config was in your path post-install). In this situation, Libtool has a known issue with certain systems' ldconfig setup: - -http://article.gmane.org/gmane.comp.sysutils.automake.general/9025 - -This requires a manual run of "sudo ldconfig" after the "sudo make install" for Google Test before any binaries which link against it can be executed. This isn't a bug in our install, but we should at least have documented it or hacked a work-around into our install. We should have one of these solutions in our next release. \ No newline at end of file diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-actions.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-actions.h deleted file mode 100644 index 6895dfd5d2d..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-actions.h +++ /dev/null @@ -1,1141 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used actions. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ - -#ifndef _WIN32_WCE -# include -#endif - -#include -#include -#include -#include -#include -#include - -#include "gmock/internal/gmock-internal-utils.h" -#include "gmock/internal/gmock-port.h" - -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) -#endif - -namespace testing { - -// To implement an action Foo, define: -// 1. a class FooAction that implements the ActionInterface interface, and -// 2. a factory function that creates an Action object from a -// const FooAction*. -// -// The two-level delegation design follows that of Matcher, providing -// consistency for extension developers. It also eases ownership -// management as Action objects can now be copied like plain values. - -namespace internal { - -// BuiltInDefaultValueGetter::Get() returns a -// default-constructed T value. BuiltInDefaultValueGetter::Get() crashes with an error. -// -// This primary template is used when kDefaultConstructible is true. -template -struct BuiltInDefaultValueGetter { - static T Get() { return T(); } -}; -template -struct BuiltInDefaultValueGetter { - static T Get() { - Assert(false, __FILE__, __LINE__, - "Default action undefined for the function return type."); - return internal::Invalid(); - // The above statement will never be reached, but is required in - // order for this function to compile. - } -}; - -// BuiltInDefaultValue::Get() returns the "built-in" default value -// for type T, which is NULL when T is a raw pointer type, 0 when T is -// a numeric type, false when T is bool, or "" when T is string or -// std::string. In addition, in C++11 and above, it turns a -// default-constructed T value if T is default constructible. For any -// other type T, the built-in default T value is undefined, and the -// function will abort the process. -template -class BuiltInDefaultValue { - public: - // This function returns true iff type T has a built-in default value. - static bool Exists() { - return ::std::is_default_constructible::value; - } - - static T Get() { - return BuiltInDefaultValueGetter< - T, ::std::is_default_constructible::value>::Get(); - } -}; - -// This partial specialization says that we use the same built-in -// default value for T and const T. -template -class BuiltInDefaultValue { - public: - static bool Exists() { return BuiltInDefaultValue::Exists(); } - static T Get() { return BuiltInDefaultValue::Get(); } -}; - -// This partial specialization defines the default values for pointer -// types. -template -class BuiltInDefaultValue { - public: - static bool Exists() { return true; } - static T* Get() { return nullptr; } -}; - -// The following specializations define the default values for -// specific types we care about. -#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ - template <> \ - class BuiltInDefaultValue { \ - public: \ - static bool Exists() { return true; } \ - static type Get() { return value; } \ - } - -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); - -// There's no need for a default action for signed wchar_t, as that -// type is the same as wchar_t for gcc, and invalid for MSVC. -// -// There's also no need for a default action for unsigned wchar_t, as -// that type is the same as unsigned int for gcc, and invalid for -// MSVC. -#if GMOCK_WCHAR_T_IS_NATIVE_ -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT -#endif - -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); -GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); - -#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ - -} // namespace internal - -// When an unexpected function call is encountered, Google Mock will -// let it return a default value if the user has specified one for its -// return type, or if the return type has a built-in default value; -// otherwise Google Mock won't know what value to return and will have -// to abort the process. -// -// The DefaultValue class allows a user to specify the -// default value for a type T that is both copyable and publicly -// destructible (i.e. anything that can be used as a function return -// type). The usage is: -// -// // Sets the default value for type T to be foo. -// DefaultValue::Set(foo); -template -class DefaultValue { - public: - // Sets the default value for type T; requires T to be - // copy-constructable and have a public destructor. - static void Set(T x) { - delete producer_; - producer_ = new FixedValueProducer(x); - } - - // Provides a factory function to be called to generate the default value. - // This method can be used even if T is only move-constructible, but it is not - // limited to that case. - typedef T (*FactoryFunction)(); - static void SetFactory(FactoryFunction factory) { - delete producer_; - producer_ = new FactoryValueProducer(factory); - } - - // Unsets the default value for type T. - static void Clear() { - delete producer_; - producer_ = nullptr; - } - - // Returns true iff the user has set the default value for type T. - static bool IsSet() { return producer_ != nullptr; } - - // Returns true if T has a default return value set by the user or there - // exists a built-in default value. - static bool Exists() { - return IsSet() || internal::BuiltInDefaultValue::Exists(); - } - - // Returns the default value for type T if the user has set one; - // otherwise returns the built-in default value. Requires that Exists() - // is true, which ensures that the return value is well-defined. - static T Get() { - return producer_ == nullptr ? internal::BuiltInDefaultValue::Get() - : producer_->Produce(); - } - - private: - class ValueProducer { - public: - virtual ~ValueProducer() {} - virtual T Produce() = 0; - }; - - class FixedValueProducer : public ValueProducer { - public: - explicit FixedValueProducer(T value) : value_(value) {} - T Produce() override { return value_; } - - private: - const T value_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer); - }; - - class FactoryValueProducer : public ValueProducer { - public: - explicit FactoryValueProducer(FactoryFunction factory) - : factory_(factory) {} - T Produce() override { return factory_(); } - - private: - const FactoryFunction factory_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer); - }; - - static ValueProducer* producer_; -}; - -// This partial specialization allows a user to set default values for -// reference types. -template -class DefaultValue { - public: - // Sets the default value for type T&. - static void Set(T& x) { // NOLINT - address_ = &x; - } - - // Unsets the default value for type T&. - static void Clear() { address_ = nullptr; } - - // Returns true iff the user has set the default value for type T&. - static bool IsSet() { return address_ != nullptr; } - - // Returns true if T has a default return value set by the user or there - // exists a built-in default value. - static bool Exists() { - return IsSet() || internal::BuiltInDefaultValue::Exists(); - } - - // Returns the default value for type T& if the user has set one; - // otherwise returns the built-in default value if there is one; - // otherwise aborts the process. - static T& Get() { - return address_ == nullptr ? internal::BuiltInDefaultValue::Get() - : *address_; - } - - private: - static T* address_; -}; - -// This specialization allows DefaultValue::Get() to -// compile. -template <> -class DefaultValue { - public: - static bool Exists() { return true; } - static void Get() {} -}; - -// Points to the user-set default value for type T. -template -typename DefaultValue::ValueProducer* DefaultValue::producer_ = nullptr; - -// Points to the user-set default value for type T&. -template -T* DefaultValue::address_ = nullptr; - -// Implement this interface to define an action for function type F. -template -class ActionInterface { - public: - typedef typename internal::Function::Result Result; - typedef typename internal::Function::ArgumentTuple ArgumentTuple; - - ActionInterface() {} - virtual ~ActionInterface() {} - - // Performs the action. This method is not const, as in general an - // action can have side effects and be stateful. For example, a - // get-the-next-element-from-the-collection action will need to - // remember the current element. - virtual Result Perform(const ArgumentTuple& args) = 0; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface); -}; - -// An Action is a copyable and IMMUTABLE (except by assignment) -// object that represents an action to be taken when a mock function -// of type F is called. The implementation of Action is just a -// std::shared_ptr to const ActionInterface. Don't inherit from Action! -// You can view an object implementing ActionInterface as a -// concrete action (including its current state), and an Action -// object as a handle to it. -template -class Action { - // Adapter class to allow constructing Action from a legacy ActionInterface. - // New code should create Actions from functors instead. - struct ActionAdapter { - // Adapter must be copyable to satisfy std::function requirements. - ::std::shared_ptr> impl_; - - template - typename internal::Function::Result operator()(Args&&... args) { - return impl_->Perform( - ::std::forward_as_tuple(::std::forward(args)...)); - } - }; - - public: - typedef typename internal::Function::Result Result; - typedef typename internal::Function::ArgumentTuple ArgumentTuple; - - // Constructs a null Action. Needed for storing Action objects in - // STL containers. - Action() {} - - // Construct an Action from a specified callable. - // This cannot take std::function directly, because then Action would not be - // directly constructible from lambda (it would require two conversions). - template , G>::value>::type> - Action(G&& fun) : fun_(::std::forward(fun)) {} // NOLINT - - // Constructs an Action from its implementation. - explicit Action(ActionInterface* impl) - : fun_(ActionAdapter{::std::shared_ptr>(impl)}) {} - - // This constructor allows us to turn an Action object into an - // Action, as long as F's arguments can be implicitly converted - // to Func's and Func's return type can be implicitly converted to F's. - template - explicit Action(const Action& action) : fun_(action.fun_) {} - - // Returns true iff this is the DoDefault() action. - bool IsDoDefault() const { return fun_ == nullptr; } - - // Performs the action. Note that this method is const even though - // the corresponding method in ActionInterface is not. The reason - // is that a const Action means that it cannot be re-bound to - // another concrete action, not that the concrete action it binds to - // cannot change state. (Think of the difference between a const - // pointer and a pointer to const.) - Result Perform(ArgumentTuple args) const { - if (IsDoDefault()) { - internal::IllegalDoDefault(__FILE__, __LINE__); - } - return internal::Apply(fun_, ::std::move(args)); - } - - private: - template - friend class Action; - - // fun_ is an empty function iff this is the DoDefault() action. - ::std::function fun_; -}; - -// The PolymorphicAction class template makes it easy to implement a -// polymorphic action (i.e. an action that can be used in mock -// functions of than one type, e.g. Return()). -// -// To define a polymorphic action, a user first provides a COPYABLE -// implementation class that has a Perform() method template: -// -// class FooAction { -// public: -// template -// Result Perform(const ArgumentTuple& args) const { -// // Processes the arguments and returns a result, using -// // std::get(args) to get the N-th (0-based) argument in the tuple. -// } -// ... -// }; -// -// Then the user creates the polymorphic action using -// MakePolymorphicAction(object) where object has type FooAction. See -// the definition of Return(void) and SetArgumentPointee(value) for -// complete examples. -template -class PolymorphicAction { - public: - explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} - - template - operator Action() const { - return Action(new MonomorphicImpl(impl_)); - } - - private: - template - class MonomorphicImpl : public ActionInterface { - public: - typedef typename internal::Function::Result Result; - typedef typename internal::Function::ArgumentTuple ArgumentTuple; - - explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} - - Result Perform(const ArgumentTuple& args) override { - return impl_.template Perform(args); - } - - private: - Impl impl_; - - GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); - }; - - Impl impl_; - - GTEST_DISALLOW_ASSIGN_(PolymorphicAction); -}; - -// Creates an Action from its implementation and returns it. The -// created Action object owns the implementation. -template -Action MakeAction(ActionInterface* impl) { - return Action(impl); -} - -// Creates a polymorphic action from its implementation. This is -// easier to use than the PolymorphicAction constructor as it -// doesn't require you to explicitly write the template argument, e.g. -// -// MakePolymorphicAction(foo); -// vs -// PolymorphicAction(foo); -template -inline PolymorphicAction MakePolymorphicAction(const Impl& impl) { - return PolymorphicAction(impl); -} - -namespace internal { - -// Helper struct to specialize ReturnAction to execute a move instead of a copy -// on return. Useful for move-only types, but could be used on any type. -template -struct ByMoveWrapper { - explicit ByMoveWrapper(T value) : payload(std::move(value)) {} - T payload; -}; - -// Implements the polymorphic Return(x) action, which can be used in -// any function that returns the type of x, regardless of the argument -// types. -// -// Note: The value passed into Return must be converted into -// Function::Result when this action is cast to Action rather than -// when that action is performed. This is important in scenarios like -// -// MOCK_METHOD1(Method, T(U)); -// ... -// { -// Foo foo; -// X x(&foo); -// EXPECT_CALL(mock, Method(_)).WillOnce(Return(x)); -// } -// -// In the example above the variable x holds reference to foo which leaves -// scope and gets destroyed. If copying X just copies a reference to foo, -// that copy will be left with a hanging reference. If conversion to T -// makes a copy of foo, the above code is safe. To support that scenario, we -// need to make sure that the type conversion happens inside the EXPECT_CALL -// statement, and conversion of the result of Return to Action is a -// good place for that. -// -// The real life example of the above scenario happens when an invocation -// of gtl::Container() is passed into Return. -// -template -class ReturnAction { - public: - // Constructs a ReturnAction object from the value to be returned. - // 'value' is passed by value instead of by const reference in order - // to allow Return("string literal") to compile. - explicit ReturnAction(R value) : value_(new R(std::move(value))) {} - - // This template type conversion operator allows Return(x) to be - // used in ANY function that returns x's type. - template - operator Action() const { // NOLINT - // Assert statement belongs here because this is the best place to verify - // conditions on F. It produces the clearest error messages - // in most compilers. - // Impl really belongs in this scope as a local class but can't - // because MSVC produces duplicate symbols in different translation units - // in this case. Until MS fixes that bug we put Impl into the class scope - // and put the typedef both here (for use in assert statement) and - // in the Impl class. But both definitions must be the same. - typedef typename Function::Result Result; - GTEST_COMPILE_ASSERT_( - !is_reference::value, - use_ReturnRef_instead_of_Return_to_return_a_reference); - static_assert(!std::is_void::value, - "Can't use Return() on an action expected to return `void`."); - return Action(new Impl(value_)); - } - - private: - // Implements the Return(x) action for a particular function type F. - template - class Impl : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; - - // The implicit cast is necessary when Result has more than one - // single-argument constructor (e.g. Result is std::vector) and R - // has a type conversion operator template. In that case, value_(value) - // won't compile as the compiler doesn't known which constructor of - // Result to call. ImplicitCast_ forces the compiler to convert R to - // Result without considering explicit constructors, thus resolving the - // ambiguity. value_ is then initialized using its copy constructor. - explicit Impl(const std::shared_ptr& value) - : value_before_cast_(*value), - value_(ImplicitCast_(value_before_cast_)) {} - - Result Perform(const ArgumentTuple&) override { return value_; } - - private: - GTEST_COMPILE_ASSERT_(!is_reference::value, - Result_cannot_be_a_reference_type); - // We save the value before casting just in case it is being cast to a - // wrapper type. - R value_before_cast_; - Result value_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); - }; - - // Partially specialize for ByMoveWrapper. This version of ReturnAction will - // move its contents instead. - template - class Impl, F> : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; - - explicit Impl(const std::shared_ptr& wrapper) - : performed_(false), wrapper_(wrapper) {} - - Result Perform(const ArgumentTuple&) override { - GTEST_CHECK_(!performed_) - << "A ByMove() action should only be performed once."; - performed_ = true; - return std::move(wrapper_->payload); - } - - private: - bool performed_; - const std::shared_ptr wrapper_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - const std::shared_ptr value_; - - GTEST_DISALLOW_ASSIGN_(ReturnAction); -}; - -// Implements the ReturnNull() action. -class ReturnNullAction { - public: - // Allows ReturnNull() to be used in any pointer-returning function. In C++11 - // this is enforced by returning nullptr, and in non-C++11 by asserting a - // pointer type on compile time. - template - static Result Perform(const ArgumentTuple&) { - return nullptr; - } -}; - -// Implements the Return() action. -class ReturnVoidAction { - public: - // Allows Return() to be used in any void-returning function. - template - static void Perform(const ArgumentTuple&) { - CompileAssertTypesEqual(); - } -}; - -// Implements the polymorphic ReturnRef(x) action, which can be used -// in any function that returns a reference to the type of x, -// regardless of the argument types. -template -class ReturnRefAction { - public: - // Constructs a ReturnRefAction object from the reference to be returned. - explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT - - // This template type conversion operator allows ReturnRef(x) to be - // used in ANY function that returns a reference to x's type. - template - operator Action() const { - typedef typename Function::Result Result; - // Asserts that the function return type is a reference. This - // catches the user error of using ReturnRef(x) when Return(x) - // should be used, and generates some helpful error message. - GTEST_COMPILE_ASSERT_(internal::is_reference::value, - use_Return_instead_of_ReturnRef_to_return_a_value); - return Action(new Impl(ref_)); - } - - private: - // Implements the ReturnRef(x) action for a particular function type F. - template - class Impl : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; - - explicit Impl(T& ref) : ref_(ref) {} // NOLINT - - Result Perform(const ArgumentTuple&) override { return ref_; } - - private: - T& ref_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - T& ref_; - - GTEST_DISALLOW_ASSIGN_(ReturnRefAction); -}; - -// Implements the polymorphic ReturnRefOfCopy(x) action, which can be -// used in any function that returns a reference to the type of x, -// regardless of the argument types. -template -class ReturnRefOfCopyAction { - public: - // Constructs a ReturnRefOfCopyAction object from the reference to - // be returned. - explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT - - // This template type conversion operator allows ReturnRefOfCopy(x) to be - // used in ANY function that returns a reference to x's type. - template - operator Action() const { - typedef typename Function::Result Result; - // Asserts that the function return type is a reference. This - // catches the user error of using ReturnRefOfCopy(x) when Return(x) - // should be used, and generates some helpful error message. - GTEST_COMPILE_ASSERT_( - internal::is_reference::value, - use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); - return Action(new Impl(value_)); - } - - private: - // Implements the ReturnRefOfCopy(x) action for a particular function type F. - template - class Impl : public ActionInterface { - public: - typedef typename Function::Result Result; - typedef typename Function::ArgumentTuple ArgumentTuple; - - explicit Impl(const T& value) : value_(value) {} // NOLINT - - Result Perform(const ArgumentTuple&) override { return value_; } - - private: - T value_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - const T value_; - - GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction); -}; - -// Implements the polymorphic DoDefault() action. -class DoDefaultAction { - public: - // This template type conversion operator allows DoDefault() to be - // used in any function. - template - operator Action() const { return Action(); } // NOLINT -}; - -// Implements the Assign action to set a given pointer referent to a -// particular value. -template -class AssignAction { - public: - AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} - - template - void Perform(const ArgumentTuple& /* args */) const { - *ptr_ = value_; - } - - private: - T1* const ptr_; - const T2 value_; - - GTEST_DISALLOW_ASSIGN_(AssignAction); -}; - -#if !GTEST_OS_WINDOWS_MOBILE - -// Implements the SetErrnoAndReturn action to simulate return from -// various system calls and libc functions. -template -class SetErrnoAndReturnAction { - public: - SetErrnoAndReturnAction(int errno_value, T result) - : errno_(errno_value), - result_(result) {} - template - Result Perform(const ArgumentTuple& /* args */) const { - errno = errno_; - return result_; - } - - private: - const int errno_; - const T result_; - - GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction); -}; - -#endif // !GTEST_OS_WINDOWS_MOBILE - -// Implements the SetArgumentPointee(x) action for any function -// whose N-th argument (0-based) is a pointer to x's type. -template -struct SetArgumentPointeeAction { - A value; - - template - void operator()(const Args&... args) const { - *::std::get(std::tie(args...)) = value; - } -}; - -// Implements the Invoke(object_ptr, &Class::Method) action. -template -struct InvokeMethodAction { - Class* const obj_ptr; - const MethodPtr method_ptr; - - template - auto operator()(Args&&... args) const - -> decltype((obj_ptr->*method_ptr)(std::forward(args)...)) { - return (obj_ptr->*method_ptr)(std::forward(args)...); - } -}; - -// Implements the InvokeWithoutArgs(f) action. The template argument -// FunctionImpl is the implementation type of f, which can be either a -// function pointer or a functor. InvokeWithoutArgs(f) can be used as an -// Action as long as f's type is compatible with F. -template -struct InvokeWithoutArgsAction { - FunctionImpl function_impl; - - // Allows InvokeWithoutArgs(f) to be used as any action whose type is - // compatible with f. - template - auto operator()(const Args&...) -> decltype(function_impl()) { - return function_impl(); - } -}; - -// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. -template -struct InvokeMethodWithoutArgsAction { - Class* const obj_ptr; - const MethodPtr method_ptr; - - using ReturnType = typename std::result_of::type; - - template - ReturnType operator()(const Args&...) const { - return (obj_ptr->*method_ptr)(); - } -}; - -// Implements the IgnoreResult(action) action. -template -class IgnoreResultAction { - public: - explicit IgnoreResultAction(const A& action) : action_(action) {} - - template - operator Action() const { - // Assert statement belongs here because this is the best place to verify - // conditions on F. It produces the clearest error messages - // in most compilers. - // Impl really belongs in this scope as a local class but can't - // because MSVC produces duplicate symbols in different translation units - // in this case. Until MS fixes that bug we put Impl into the class scope - // and put the typedef both here (for use in assert statement) and - // in the Impl class. But both definitions must be the same. - typedef typename internal::Function::Result Result; - - // Asserts at compile time that F returns void. - CompileAssertTypesEqual(); - - return Action(new Impl(action_)); - } - - private: - template - class Impl : public ActionInterface { - public: - typedef typename internal::Function::Result Result; - typedef typename internal::Function::ArgumentTuple ArgumentTuple; - - explicit Impl(const A& action) : action_(action) {} - - void Perform(const ArgumentTuple& args) override { - // Performs the action and ignores its result. - action_.Perform(args); - } - - private: - // Type OriginalFunction is the same as F except that its return - // type is IgnoredValue. - typedef typename internal::Function::MakeResultIgnoredValue - OriginalFunction; - - const Action action_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - const A action_; - - GTEST_DISALLOW_ASSIGN_(IgnoreResultAction); -}; - -template -struct WithArgsAction { - InnerAction action; - - // The inner action could be anything convertible to Action. - // We use the conversion operator to detect the signature of the inner Action. - template - operator Action() const { // NOLINT - Action>::type...)> - converted(action); - - return [converted](Args... args) -> R { - return converted.Perform(std::forward_as_tuple( - std::get(std::forward_as_tuple(std::forward(args)...))...)); - }; - } -}; - -template -struct DoAllAction { - private: - template - std::vector> Convert(IndexSequence) const { - return {std::get(actions)...}; - } - - public: - std::tuple actions; - - template - operator Action() const { // NOLINT - struct Op { - std::vector> converted; - Action last; - R operator()(Args... args) const { - auto tuple_args = std::forward_as_tuple(std::forward(args)...); - for (auto& a : converted) { - a.Perform(tuple_args); - } - return last.Perform(tuple_args); - } - }; - return Op{Convert(MakeIndexSequence()), - std::get(actions)}; - } -}; - -} // namespace internal - -// An Unused object can be implicitly constructed from ANY value. -// This is handy when defining actions that ignore some or all of the -// mock function arguments. For example, given -// -// MOCK_METHOD3(Foo, double(const string& label, double x, double y)); -// MOCK_METHOD3(Bar, double(int index, double x, double y)); -// -// instead of -// -// double DistanceToOriginWithLabel(const string& label, double x, double y) { -// return sqrt(x*x + y*y); -// } -// double DistanceToOriginWithIndex(int index, double x, double y) { -// return sqrt(x*x + y*y); -// } -// ... -// EXPECT_CALL(mock, Foo("abc", _, _)) -// .WillOnce(Invoke(DistanceToOriginWithLabel)); -// EXPECT_CALL(mock, Bar(5, _, _)) -// .WillOnce(Invoke(DistanceToOriginWithIndex)); -// -// you could write -// -// // We can declare any uninteresting argument as Unused. -// double DistanceToOrigin(Unused, double x, double y) { -// return sqrt(x*x + y*y); -// } -// ... -// EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); -// EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); -typedef internal::IgnoredValue Unused; - -// Creates an action that does actions a1, a2, ..., sequentially in -// each invocation. -template -internal::DoAllAction::type...> DoAll( - Action&&... action) { - return {std::forward_as_tuple(std::forward(action)...)}; -} - -// WithArg(an_action) creates an action that passes the k-th -// (0-based) argument of the mock function to an_action and performs -// it. It adapts an action accepting one argument to one that accepts -// multiple arguments. For convenience, we also provide -// WithArgs(an_action) (defined below) as a synonym. -template -internal::WithArgsAction::type, k> -WithArg(InnerAction&& action) { - return {std::forward(action)}; -} - -// WithArgs(an_action) creates an action that passes -// the selected arguments of the mock function to an_action and -// performs it. It serves as an adaptor between actions with -// different argument lists. -template -internal::WithArgsAction::type, k, ks...> -WithArgs(InnerAction&& action) { - return {std::forward(action)}; -} - -// WithoutArgs(inner_action) can be used in a mock function with a -// non-empty argument list to perform inner_action, which takes no -// argument. In other words, it adapts an action accepting no -// argument to one that accepts (and ignores) arguments. -template -internal::WithArgsAction::type> -WithoutArgs(InnerAction&& action) { - return {std::forward(action)}; -} - -// Creates an action that returns 'value'. 'value' is passed by value -// instead of const reference - otherwise Return("string literal") -// will trigger a compiler error about using array as initializer. -template -internal::ReturnAction Return(R value) { - return internal::ReturnAction(std::move(value)); -} - -// Creates an action that returns NULL. -inline PolymorphicAction ReturnNull() { - return MakePolymorphicAction(internal::ReturnNullAction()); -} - -// Creates an action that returns from a void function. -inline PolymorphicAction Return() { - return MakePolymorphicAction(internal::ReturnVoidAction()); -} - -// Creates an action that returns the reference to a variable. -template -inline internal::ReturnRefAction ReturnRef(R& x) { // NOLINT - return internal::ReturnRefAction(x); -} - -// Creates an action that returns the reference to a copy of the -// argument. The copy is created when the action is constructed and -// lives as long as the action. -template -inline internal::ReturnRefOfCopyAction ReturnRefOfCopy(const R& x) { - return internal::ReturnRefOfCopyAction(x); -} - -// Modifies the parent action (a Return() action) to perform a move of the -// argument instead of a copy. -// Return(ByMove()) actions can only be executed once and will assert this -// invariant. -template -internal::ByMoveWrapper ByMove(R x) { - return internal::ByMoveWrapper(std::move(x)); -} - -// Creates an action that does the default action for the give mock function. -inline internal::DoDefaultAction DoDefault() { - return internal::DoDefaultAction(); -} - -// Creates an action that sets the variable pointed by the N-th -// (0-based) function argument to 'value'. -template -internal::SetArgumentPointeeAction SetArgPointee(T x) { - return {std::move(x)}; -} - -// The following version is DEPRECATED. -template -internal::SetArgumentPointeeAction SetArgumentPointee(T x) { - return {std::move(x)}; -} - -// Creates an action that sets a pointer referent to a given value. -template -PolymorphicAction > Assign(T1* ptr, T2 val) { - return MakePolymorphicAction(internal::AssignAction(ptr, val)); -} - -#if !GTEST_OS_WINDOWS_MOBILE - -// Creates an action that sets errno and returns the appropriate error. -template -PolymorphicAction > -SetErrnoAndReturn(int errval, T result) { - return MakePolymorphicAction( - internal::SetErrnoAndReturnAction(errval, result)); -} - -#endif // !GTEST_OS_WINDOWS_MOBILE - -// Various overloads for Invoke(). - -// Legacy function. -// Actions can now be implicitly constructed from callables. No need to create -// wrapper objects. -// This function exists for backwards compatibility. -template -typename std::decay::type Invoke(FunctionImpl&& function_impl) { - return std::forward(function_impl); -} - -// Creates an action that invokes the given method on the given object -// with the mock function's arguments. -template -internal::InvokeMethodAction Invoke(Class* obj_ptr, - MethodPtr method_ptr) { - return {obj_ptr, method_ptr}; -} - -// Creates an action that invokes 'function_impl' with no argument. -template -internal::InvokeWithoutArgsAction::type> -InvokeWithoutArgs(FunctionImpl function_impl) { - return {std::move(function_impl)}; -} - -// Creates an action that invokes the given method on the given object -// with no argument. -template -internal::InvokeMethodWithoutArgsAction InvokeWithoutArgs( - Class* obj_ptr, MethodPtr method_ptr) { - return {obj_ptr, method_ptr}; -} - -// Creates an action that performs an_action and throws away its -// result. In other words, it changes the return type of an_action to -// void. an_action MUST NOT return void, or the code won't compile. -template -inline internal::IgnoreResultAction
IgnoreResult(const A& an_action) { - return internal::IgnoreResultAction(an_action); -} - -// Creates a reference wrapper for the given L-value. If necessary, -// you can explicitly specify the type of the reference. For example, -// suppose 'derived' is an object of type Derived, ByRef(derived) -// would wrap a Derived&. If you want to wrap a const Base& instead, -// where Base is a base class of Derived, just write: -// -// ByRef(derived) -// -// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper. -// However, it may still be used for consistency with ByMove(). -template -inline ::std::reference_wrapper ByRef(T& l_value) { // NOLINT - return ::std::reference_wrapper(l_value); -} - -} // namespace testing - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-cardinalities.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-cardinalities.h deleted file mode 100644 index 8fa25ebbb5e..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-cardinalities.h +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used cardinalities. More -// cardinalities can be defined by the user implementing the -// CardinalityInterface interface if necessary. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ - -#include -#include -#include // NOLINT -#include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - -namespace testing { - -// To implement a cardinality Foo, define: -// 1. a class FooCardinality that implements the -// CardinalityInterface interface, and -// 2. a factory function that creates a Cardinality object from a -// const FooCardinality*. -// -// The two-level delegation design follows that of Matcher, providing -// consistency for extension developers. It also eases ownership -// management as Cardinality objects can now be copied like plain values. - -// The implementation of a cardinality. -class CardinalityInterface { - public: - virtual ~CardinalityInterface() {} - - // Conservative estimate on the lower/upper bound of the number of - // calls allowed. - virtual int ConservativeLowerBound() const { return 0; } - virtual int ConservativeUpperBound() const { return INT_MAX; } - - // Returns true iff call_count calls will satisfy this cardinality. - virtual bool IsSatisfiedByCallCount(int call_count) const = 0; - - // Returns true iff call_count calls will saturate this cardinality. - virtual bool IsSaturatedByCallCount(int call_count) const = 0; - - // Describes self to an ostream. - virtual void DescribeTo(::std::ostream* os) const = 0; -}; - -// A Cardinality is a copyable and IMMUTABLE (except by assignment) -// object that specifies how many times a mock function is expected to -// be called. The implementation of Cardinality is just a std::shared_ptr -// to const CardinalityInterface. Don't inherit from Cardinality! -class GTEST_API_ Cardinality { - public: - // Constructs a null cardinality. Needed for storing Cardinality - // objects in STL containers. - Cardinality() {} - - // Constructs a Cardinality from its implementation. - explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {} - - // Conservative estimate on the lower/upper bound of the number of - // calls allowed. - int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); } - int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } - - // Returns true iff call_count calls will satisfy this cardinality. - bool IsSatisfiedByCallCount(int call_count) const { - return impl_->IsSatisfiedByCallCount(call_count); - } - - // Returns true iff call_count calls will saturate this cardinality. - bool IsSaturatedByCallCount(int call_count) const { - return impl_->IsSaturatedByCallCount(call_count); - } - - // Returns true iff call_count calls will over-saturate this - // cardinality, i.e. exceed the maximum number of allowed calls. - bool IsOverSaturatedByCallCount(int call_count) const { - return impl_->IsSaturatedByCallCount(call_count) && - !impl_->IsSatisfiedByCallCount(call_count); - } - - // Describes self to an ostream - void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } - - // Describes the given actual call count to an ostream. - static void DescribeActualCallCountTo(int actual_call_count, - ::std::ostream* os); - - private: - std::shared_ptr impl_; -}; - -// Creates a cardinality that allows at least n calls. -GTEST_API_ Cardinality AtLeast(int n); - -// Creates a cardinality that allows at most n calls. -GTEST_API_ Cardinality AtMost(int n); - -// Creates a cardinality that allows any number of calls. -GTEST_API_ Cardinality AnyNumber(); - -// Creates a cardinality that allows between min and max calls. -GTEST_API_ Cardinality Between(int min, int max); - -// Creates a cardinality that allows exactly n calls. -GTEST_API_ Cardinality Exactly(int n); - -// Creates a cardinality from its implementation. -inline Cardinality MakeCardinality(const CardinalityInterface* c) { - return Cardinality(c); -} - -} // namespace testing - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-function-mocker.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-function-mocker.h deleted file mode 100644 index 84a608e1890..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-function-mocker.h +++ /dev/null @@ -1,218 +0,0 @@ -#ifndef THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT -#define THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT - -#include "gmock/gmock-generated-function-mockers.h" // NOLINT -#include "gmock/internal/gmock-pp.h" - -#define MOCK_METHOD(...) \ - GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \ - GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ()) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \ - GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \ - GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \ - GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \ - GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \ - GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ - GMOCK_INTERNAL_MOCK_METHOD_IMPL( \ - GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \ - GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \ - GMOCK_INTERNAL_HAS_NOEXCEPT(_Spec), GMOCK_INTERNAL_GET_CALLTYPE(_Spec), \ - (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args))) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \ - GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__) - -#define GMOCK_INTERNAL_WRONG_ARITY(...) \ - static_assert( \ - false, \ - "MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \ - "_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \ - "enclosed in parentheses. If _Ret is a type with unprotected commas, " \ - "it must also be enclosed in parentheses.") - -#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \ - static_assert( \ - GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \ - GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.") - -#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \ - static_assert( \ - std::is_function<__VA_ARGS__>::value, \ - "Signature must be a function type, maybe return type contains " \ - "unprotected comma."); \ - static_assert( \ - ::testing::tuple_size::ArgumentTuple>::value == _N, \ - "This method does not take " GMOCK_PP_STRINGIZE( \ - _N) " arguments. Parenthesize all types with unproctected commas.") - -#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec) - -#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \ - _Override, _Final, _Noexcept, \ - _CallType, _Signature) \ - typename ::testing::internal::Function::Result \ - GMOCK_INTERNAL_EXPAND(_CallType) \ - _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \ - GMOCK_PP_IF(_Constness, const, ) GMOCK_PP_IF(_Noexcept, noexcept, ) \ - GMOCK_PP_IF(_Override, override, ) \ - GMOCK_PP_IF(_Final, final, ) { \ - GMOCK_MOCKER_(_N, _Constness, _MethodName) \ - .SetOwnerAndName(this, #_MethodName); \ - return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ - .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \ - } \ - ::testing::MockSpec gmock_##_MethodName( \ - GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \ - GMOCK_PP_IF(_Constness, const, ) { \ - GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \ - return GMOCK_MOCKER_(_N, _Constness, _MethodName) \ - .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \ - } \ - ::testing::MockSpec gmock_##_MethodName( \ - const ::testing::internal::WithoutMatchers&, \ - GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \ - GMOCK_PP_REMOVE_PARENS(_Signature)>*) \ - const GMOCK_PP_IF(_Noexcept, noexcept, ) { \ - return GMOCK_PP_CAT(::testing::internal::AdjustConstness_, \ - GMOCK_PP_IF(_Constness, const, ))(this) \ - ->gmock_##_MethodName(GMOCK_PP_REPEAT( \ - GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \ - } \ - mutable ::testing::FunctionMocker \ - GMOCK_MOCKER_(_N, _Constness, _MethodName) - -#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__ - -// Five Valid modifiers. -#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \ - GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple)) - -#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \ - GMOCK_PP_HAS_COMMA( \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple)) - -#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \ - GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple)) - -#define GMOCK_INTERNAL_HAS_NOEXCEPT(_Tuple) \ - GMOCK_PP_HAS_COMMA( \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_NOEXCEPT, ~, _Tuple)) - -#define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \ - GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple) - -#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \ - static_assert( \ - (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \ - GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \ - GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \ - GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \ - GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \ - GMOCK_PP_STRINGIZE( \ - _elem) " cannot be recognized as a valid specification modifier."); - -// Modifiers implementation. -#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \ - GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem) - -#define GMOCK_INTERNAL_DETECT_CONST_I_const , - -#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \ - GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem) - -#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override , - -#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \ - GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem) - -#define GMOCK_INTERNAL_DETECT_FINAL_I_final , - -// TODO(iserna): Maybe noexcept should accept an argument here as well. -#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \ - GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem) - -#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept , - -#define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \ - GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \ - GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \ - (_elem) - -// TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and -// GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows -// maybe they can be simplified somehow. -#define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \ - GMOCK_INTERNAL_IS_CALLTYPE_I( \ - GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg)) -#define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg) - -#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \ - GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \ - GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg)) -#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \ - GMOCK_PP_CAT(GMOCK_PP_IDENTITY, _arg) - -#define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype - -#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \ - GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), GMOCK_PP_REMOVE_PARENS, \ - GMOCK_PP_IDENTITY) \ - (_Ret)(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args)) - -#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \ - GMOCK_PP_COMMA_IF(_i) \ - GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \ - GMOCK_PP_IDENTITY) \ - (_elem) - -#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \ - GMOCK_PP_COMMA_IF(_i) \ - GMOCK_INTERNAL_ARG_O(typename, GMOCK_PP_INC(_i), \ - GMOCK_PP_REMOVE_PARENS(_Signature)) \ - gmock_a##_i - -#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \ - GMOCK_PP_COMMA_IF(_i) \ - ::std::forward( \ - gmock_a##_i) - -#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \ - GMOCK_PP_COMMA_IF(_i) \ - GMOCK_INTERNAL_MATCHER_O(typename, GMOCK_PP_INC(_i), \ - GMOCK_PP_REMOVE_PARENS(_Signature)) \ - gmock_a##_i - -#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \ - GMOCK_PP_COMMA_IF(_i) \ - gmock_a##_i - -#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \ - GMOCK_PP_COMMA_IF(_i) \ - ::testing::A() - -#define GMOCK_INTERNAL_ARG_O(_tn, _i, ...) GMOCK_ARG_(_tn, _i, __VA_ARGS__) - -#define GMOCK_INTERNAL_MATCHER_O(_tn, _i, ...) \ - GMOCK_MATCHER_(_tn, _i, __VA_ARGS__) - -#endif // THIRD_PARTY_GOOGLETEST_GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-actions.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-actions.h deleted file mode 100644 index 409886cfe57..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-actions.h +++ /dev/null @@ -1,1885 +0,0 @@ -// This file was GENERATED by command: -// pump.py gmock-generated-actions.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used variadic actions. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ - -#include -#include - -#include "gmock/gmock-actions.h" -#include "gmock/internal/gmock-port.h" - -namespace testing { -namespace internal { - -// A macro from the ACTION* family (defined later in this file) -// defines an action that can be used in a mock function. Typically, -// these actions only care about a subset of the arguments of the mock -// function. For example, if such an action only uses the second -// argument, it can be used in any mock function that takes >= 2 -// arguments where the type of the second argument is compatible. -// -// Therefore, the action implementation must be prepared to take more -// arguments than it needs. The ExcessiveArg type is used to -// represent those excessive arguments. In order to keep the compiler -// error messages tractable, we define it in the testing namespace -// instead of testing::internal. However, this is an INTERNAL TYPE -// and subject to change without notice, so a user MUST NOT USE THIS -// TYPE DIRECTLY. -struct ExcessiveArg {}; - -// A helper class needed for implementing the ACTION* macros. -template -class ActionHelper { - public: - static Result Perform(Impl* impl, const ::std::tuple<>& args) { - return impl->template gmock_PerformImpl<>(args, ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), - std::get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, - std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - std::get<6>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - std::get<6>(args), std::get<7>(args), ExcessiveArg(), ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - std::get<6>(args), std::get<7>(args), std::get<8>(args), - ExcessiveArg()); - } - - template - static Result Perform(Impl* impl, const ::std::tuple& args) { - return impl->template gmock_PerformImpl(args, std::get<0>(args), std::get<1>(args), std::get<2>(args), - std::get<3>(args), std::get<4>(args), std::get<5>(args), - std::get<6>(args), std::get<7>(args), std::get<8>(args), - std::get<9>(args)); - } -}; - -} // namespace internal -} // namespace testing - -// The ACTION* family of macros can be used in a namespace scope to -// define custom actions easily. The syntax: -// -// ACTION(name) { statements; } -// -// will define an action with the given name that executes the -// statements. The value returned by the statements will be used as -// the return value of the action. Inside the statements, you can -// refer to the K-th (0-based) argument of the mock function by -// 'argK', and refer to its type by 'argK_type'. For example: -// -// ACTION(IncrementArg1) { -// arg1_type temp = arg1; -// return ++(*temp); -// } -// -// allows you to write -// -// ...WillOnce(IncrementArg1()); -// -// You can also refer to the entire argument tuple and its type by -// 'args' and 'args_type', and refer to the mock function type and its -// return type by 'function_type' and 'return_type'. -// -// Note that you don't need to specify the types of the mock function -// arguments. However rest assured that your code is still type-safe: -// you'll get a compiler error if *arg1 doesn't support the ++ -// operator, or if the type of ++(*arg1) isn't compatible with the -// mock function's return type, for example. -// -// Sometimes you'll want to parameterize the action. For that you can use -// another macro: -// -// ACTION_P(name, param_name) { statements; } -// -// For example: -// -// ACTION_P(Add, n) { return arg0 + n; } -// -// will allow you to write: -// -// ...WillOnce(Add(5)); -// -// Note that you don't need to provide the type of the parameter -// either. If you need to reference the type of a parameter named -// 'foo', you can write 'foo_type'. For example, in the body of -// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type -// of 'n'. -// -// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support -// multi-parameter actions. -// -// For the purpose of typing, you can view -// -// ACTION_Pk(Foo, p1, ..., pk) { ... } -// -// as shorthand for -// -// template -// FooActionPk Foo(p1_type p1, ..., pk_type pk) { ... } -// -// In particular, you can provide the template type arguments -// explicitly when invoking Foo(), as in Foo(5, false); -// although usually you can rely on the compiler to infer the types -// for you automatically. You can assign the result of expression -// Foo(p1, ..., pk) to a variable of type FooActionPk. This can be useful when composing actions. -// -// You can also overload actions with different numbers of parameters: -// -// ACTION_P(Plus, a) { ... } -// ACTION_P2(Plus, a, b) { ... } -// -// While it's tempting to always use the ACTION* macros when defining -// a new action, you should also consider implementing ActionInterface -// or using MakePolymorphicAction() instead, especially if you need to -// use the action a lot. While these approaches require more work, -// they give you more control on the types of the mock function -// arguments and the action parameters, which in general leads to -// better compiler error messages that pay off in the long run. They -// also allow overloading actions based on parameter types (as opposed -// to just based on the number of parameters). -// -// CAVEAT: -// -// ACTION*() can only be used in a namespace scope. The reason is -// that C++ doesn't yet allow function-local types to be used to -// instantiate templates. The up-coming C++0x standard will fix this. -// Once that's done, we'll consider supporting using ACTION*() inside -// a function. -// -// MORE INFORMATION: -// -// To learn more about using these macros, please search for 'ACTION' on -// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md - -// An internal macro needed for implementing ACTION*(). -#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\ - const args_type& args GTEST_ATTRIBUTE_UNUSED_, \ - const arg0_type& arg0 GTEST_ATTRIBUTE_UNUSED_, \ - const arg1_type& arg1 GTEST_ATTRIBUTE_UNUSED_, \ - const arg2_type& arg2 GTEST_ATTRIBUTE_UNUSED_, \ - const arg3_type& arg3 GTEST_ATTRIBUTE_UNUSED_, \ - const arg4_type& arg4 GTEST_ATTRIBUTE_UNUSED_, \ - const arg5_type& arg5 GTEST_ATTRIBUTE_UNUSED_, \ - const arg6_type& arg6 GTEST_ATTRIBUTE_UNUSED_, \ - const arg7_type& arg7 GTEST_ATTRIBUTE_UNUSED_, \ - const arg8_type& arg8 GTEST_ATTRIBUTE_UNUSED_, \ - const arg9_type& arg9 GTEST_ATTRIBUTE_UNUSED_ - -// Sometimes you want to give an action explicit template parameters -// that cannot be inferred from its value parameters. ACTION() and -// ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that -// and can be viewed as an extension to ACTION() and ACTION_P*(). -// -// The syntax: -// -// ACTION_TEMPLATE(ActionName, -// HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), -// AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -// -// defines an action template that takes m explicit template -// parameters and n value parameters. name_i is the name of the i-th -// template parameter, and kind_i specifies whether it's a typename, -// an integral constant, or a template. p_i is the name of the i-th -// value parameter. -// -// Example: -// -// // DuplicateArg(output) converts the k-th argument of the mock -// // function to type T and copies it to *output. -// ACTION_TEMPLATE(DuplicateArg, -// HAS_2_TEMPLATE_PARAMS(int, k, typename, T), -// AND_1_VALUE_PARAMS(output)) { -// *output = T(::std::get(args)); -// } -// ... -// int n; -// EXPECT_CALL(mock, Foo(_, _)) -// .WillOnce(DuplicateArg<1, unsigned char>(&n)); -// -// To create an instance of an action template, write: -// -// ActionName(v1, ..., v_n) -// -// where the ts are the template arguments and the vs are the value -// arguments. The value argument types are inferred by the compiler. -// If you want to explicitly specify the value argument types, you can -// provide additional template arguments: -// -// ActionName(v1, ..., v_n) -// -// where u_i is the desired type of v_i. -// -// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the -// number of value parameters, but not on the number of template -// parameters. Without the restriction, the meaning of the following -// is unclear: -// -// OverloadedAction(x); -// -// Are we using a single-template-parameter action where 'bool' refers -// to the type of x, or are we using a two-template-parameter action -// where the compiler is asked to infer the type of x? -// -// Implementation notes: -// -// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and -// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for -// implementing ACTION_TEMPLATE. The main trick we use is to create -// new macro invocations when expanding a macro. For example, we have -// -// #define ACTION_TEMPLATE(name, template_params, value_params) -// ... GMOCK_INTERNAL_DECL_##template_params ... -// -// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...) -// to expand to -// -// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ... -// -// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the -// preprocessor will continue to expand it to -// -// ... typename T ... -// -// This technique conforms to the C++ standard and is portable. It -// allows us to implement action templates using O(N) code, where N is -// the maximum number of template/value parameters supported. Without -// using it, we'd have to devote O(N^2) amount of code to implement all -// combinations of m and n. - -// Declares the template parameters. -#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 -#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) kind0 name0, kind1 name1 -#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) kind0 name0, kind1 name1, kind2 name2 -#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3 -#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \ - kind2 name2, kind3 name3, kind4 name4 -#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 -#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ - kind5 name5, kind6 name6 -#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \ - kind4 name4, kind5 name5, kind6 name6, kind7 name7 -#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \ - kind8 name8 -#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \ - kind6 name6, kind7 name7, kind8 name8, kind9 name9 - -// Lists the template parameters. -#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 -#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) name0, name1 -#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) name0, name1, name2 -#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) name0, name1, name2, name3 -#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \ - name4 -#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \ - name2, name3, name4, name5 -#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) name0, name1, name2, name3, name4, name5, name6 -#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7 -#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \ - name6, name7, name8 -#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \ - name3, name4, name5, name6, name7, name8, name9 - -// Declares the types of value parameters. -#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \ - typename p0##_type, typename p1##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \ - typename p0##_type, typename p1##_type, typename p2##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type, typename p8##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \ - typename p2##_type, typename p3##_type, typename p4##_type, \ - typename p5##_type, typename p6##_type, typename p7##_type, \ - typename p8##_type, typename p9##_type - -// Initializes the value parameters. -#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\ - () -#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\ - (p0##_type gmock_p0) : p0(::std::move(gmock_p0)) -#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\ - (p0##_type gmock_p0, p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)) -#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\ - (p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)) -#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)) -#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)) -#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)) -#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)) -#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)) -#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)) -#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \ - p9(::std::move(gmock_p9)) - -// Declares the fields for storing the value parameters. -#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0; -#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \ - p1##_type p1; -#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \ - p1##_type p1; p2##_type p2; -#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \ - p1##_type p1; p2##_type p2; p3##_type p3; -#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; -#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; -#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; -#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; p7##_type p7; -#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; -#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \ - p9##_type p9; - -// Lists the value parameters. -#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0 -#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1 -#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2 -#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3 -#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \ - p2, p3, p4 -#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \ - p1, p2, p3, p4, p5 -#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0, p1, p2, p3, p4, p5, p6 -#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0, p1, p2, p3, p4, p5, p6, p7 -#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8 -#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 - -// Lists the value parameter types. -#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \ - p1##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \ - p1##_type, p2##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - p0##_type, p1##_type, p2##_type, p3##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ - p6##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type, p9##_type - -// Declares the value parameters. -#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0 -#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \ - p1##_type p1 -#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \ - p1##_type p1, p2##_type p2 -#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3 -#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 -#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5 -#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6 -#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6, p7##_type p7 -#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 -#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9 - -// The suffix of the class template implementing the action template. -#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() -#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P -#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2 -#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3 -#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4 -#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5 -#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6 -#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7 -#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) P8 -#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) P9 -#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) P10 - -// The name of the class template implementing the action template. -#define GMOCK_ACTION_CLASS_(name, value_params)\ - GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) - -#define ACTION_TEMPLATE(name, template_params, value_params)\ - template \ - class GMOCK_ACTION_CLASS_(name, value_params) {\ - public:\ - explicit GMOCK_ACTION_CLASS_(name, value_params)\ - GMOCK_INTERNAL_INIT_##value_params {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(\ - new gmock_Impl(GMOCK_INTERNAL_LIST_##value_params));\ - }\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\ - };\ - template \ - inline GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\ - GMOCK_INTERNAL_DECL_##value_params) {\ - return GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>(\ - GMOCK_INTERNAL_LIST_##value_params);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::\ - gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION(name)\ - class name##Action {\ - public:\ - name##Action() {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl() {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl());\ - }\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##Action);\ - };\ - inline name##Action name() {\ - return name##Action();\ - }\ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##Action::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P(name, p0)\ - template \ - class name##ActionP {\ - public:\ - explicit name##ActionP(p0##_type gmock_p0) : \ - p0(::std::forward(gmock_p0)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - explicit gmock_Impl(p0##_type gmock_p0) : \ - p0(::std::forward(gmock_p0)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0));\ - }\ - p0##_type p0;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP);\ - };\ - template \ - inline name##ActionP name(p0##_type p0) {\ - return name##ActionP(p0);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P2(name, p0, p1)\ - template \ - class name##ActionP2 {\ - public:\ - name##ActionP2(p0##_type gmock_p0, \ - p1##_type gmock_p1) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, \ - p1##_type gmock_p1) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP2);\ - };\ - template \ - inline name##ActionP2 name(p0##_type p0, \ - p1##_type p1) {\ - return name##ActionP2(p0, p1);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP2::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P3(name, p0, p1, p2)\ - template \ - class name##ActionP3 {\ - public:\ - name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP3);\ - };\ - template \ - inline name##ActionP3 name(p0##_type p0, \ - p1##_type p1, p2##_type p2) {\ - return name##ActionP3(p0, p1, p2);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP3::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P4(name, p0, p1, p2, p3)\ - template \ - class name##ActionP4 {\ - public:\ - name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP4);\ - };\ - template \ - inline name##ActionP4 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3) {\ - return name##ActionP4(p0, p1, \ - p2, p3);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP4::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P5(name, p0, p1, p2, p3, p4)\ - template \ - class name##ActionP5 {\ - public:\ - name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP5);\ - };\ - template \ - inline name##ActionP5 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4) {\ - return name##ActionP5(p0, p1, p2, p3, p4);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP5::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P6(name, p0, p1, p2, p3, p4, p5)\ - template \ - class name##ActionP6 {\ - public:\ - name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP6);\ - };\ - template \ - inline name##ActionP6 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3, p4##_type p4, p5##_type p5) {\ - return name##ActionP6(p0, p1, p2, p3, p4, p5);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP6::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6)\ - template \ - class name##ActionP7 {\ - public:\ - name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP7);\ - };\ - template \ - inline name##ActionP7 name(p0##_type p0, p1##_type p1, \ - p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6) {\ - return name##ActionP7(p0, p1, p2, p3, p4, p5, p6);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP7::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7)\ - template \ - class name##ActionP8 {\ - public:\ - name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6, p7));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP8);\ - };\ - template \ - inline name##ActionP8 name(p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6, p7##_type p7) {\ - return name##ActionP8(p0, p1, p2, p3, p4, p5, \ - p6, p7);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP8::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8)\ - template \ - class name##ActionP9 {\ - public:\ - name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)), \ - p8(::std::forward(gmock_p8)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)), \ - p8(::std::forward(gmock_p8)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP9);\ - };\ - template \ - inline name##ActionP9 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ - p8##_type p8) {\ - return name##ActionP9(p0, p1, p2, \ - p3, p4, p5, p6, p7, p8);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP9::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)\ - template \ - class name##ActionP10 {\ - public:\ - name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)), \ - p8(::std::forward(gmock_p8)), \ - p9(::std::forward(gmock_p9)) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(::std::forward(gmock_p0)), \ - p1(::std::forward(gmock_p1)), \ - p2(::std::forward(gmock_p2)), \ - p3(::std::forward(gmock_p3)), \ - p4(::std::forward(gmock_p4)), \ - p5(::std::forward(gmock_p5)), \ - p6(::std::forward(gmock_p6)), \ - p7(::std::forward(gmock_p7)), \ - p8(::std::forward(gmock_p8)), \ - p9(::std::forward(gmock_p9)) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, \ - const arg0_type& arg0, const arg1_type& arg1, \ - const arg2_type& arg2, const arg3_type& arg3, \ - const arg4_type& arg4, const arg5_type& arg5, \ - const arg6_type& arg6, const arg7_type& arg7, \ - const arg8_type& arg8, const arg9_type& arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP10);\ - };\ - template \ - inline name##ActionP10 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9) {\ - return name##ActionP10(p0, \ - p1, p2, p3, p4, p5, p6, p7, p8, p9);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP10::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -namespace testing { - - -// The ACTION*() macros trigger warning C4100 (unreferenced formal -// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in -// the macro definition, as the warnings are generated when the macro -// is expanded and macro expansion cannot contain #pragma. Therefore -// we suppress them here. -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) -#endif - -// Various overloads for InvokeArgument(). -// -// The InvokeArgument(a1, a2, ..., a_k) action invokes the N-th -// (0-based) argument, which must be a k-ary callable, of the mock -// function, with arguments a1, a2, ..., a_k. -// -// Notes: -// -// 1. The arguments are passed by value by default. If you need to -// pass an argument by reference, wrap it inside ByRef(). For -// example, -// -// InvokeArgument<1>(5, string("Hello"), ByRef(foo)) -// -// passes 5 and string("Hello") by value, and passes foo by -// reference. -// -// 2. If the callable takes an argument by reference but ByRef() is -// not used, it will receive the reference to a copy of the value, -// instead of the original value. For example, when the 0-th -// argument of the mock function takes a const string&, the action -// -// InvokeArgument<0>(string("Hello")) -// -// makes a copy of the temporary string("Hello") object and passes a -// reference of the copy, instead of the original temporary object, -// to the callable. This makes it easy for a user to define an -// InvokeArgument action from temporary values and have it performed -// later. - -namespace internal { -namespace invoke_argument { - -// Appears in InvokeArgumentAdl's argument list to help avoid -// accidental calls to user functions of the same name. -struct AdlTag {}; - -// InvokeArgumentAdl - a helper for InvokeArgument. -// The basic overloads are provided here for generic functors. -// Overloads for other custom-callables are provided in the -// internal/custom/callback-actions.h header. - -template -R InvokeArgumentAdl(AdlTag, F f) { - return f(); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1) { - return f(a1); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) { - return f(a1, a2); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) { - return f(a1, a2, a3); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) { - return f(a1, a2, a3, a4); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { - return f(a1, a2, a3, a4, a5); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { - return f(a1, a2, a3, a4, a5, a6); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7) { - return f(a1, a2, a3, a4, a5, a6, a7); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8) { - return f(a1, a2, a3, a4, a5, a6, a7, a8); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9) { - return f(a1, a2, a3, a4, a5, a6, a7, a8, a9); -} -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9, A10 a10) { - return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); -} -} // namespace invoke_argument -} // namespace internal - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_0_VALUE_PARAMS()) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args)); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(p0)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_2_VALUE_PARAMS(p0, p1)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_3_VALUE_PARAMS(p0, p1, p2)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7, p8); -} - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); -} - -// Various overloads for ReturnNew(). -// -// The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new -// instance of type T, constructed on the heap with constructor arguments -// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_0_VALUE_PARAMS()) { - return new T(); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_1_VALUE_PARAMS(p0)) { - return new T(p0); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_2_VALUE_PARAMS(p0, p1)) { - return new T(p0, p1); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_3_VALUE_PARAMS(p0, p1, p2)) { - return new T(p0, p1, p2); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { - return new T(p0, p1, p2, p3); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { - return new T(p0, p1, p2, p3, p4); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { - return new T(p0, p1, p2, p3, p4, p5); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { - return new T(p0, p1, p2, p3, p4, p5, p6); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { - return new T(p0, p1, p2, p3, p4, p5, p6, p7); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { - return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8); -} - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { - return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); -} - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -} // namespace testing - -// Include any custom callback actions added by the local installation. -// We must include this header at the end to make sure it can use the -// declarations from this file. -#include "gmock/internal/custom/gmock-generated-actions.h" - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-actions.h.pump b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-actions.h.pump deleted file mode 100644 index 87c580c44a8..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-actions.h.pump +++ /dev/null @@ -1,628 +0,0 @@ -$$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert it to -$$ gmock-generated-actions.h. -$$ -$var n = 10 $$ The maximum arity we support. -$$}} This meta comment fixes auto-indentation in editors. -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used variadic actions. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ - -#include -#include - -#include "gmock/gmock-actions.h" -#include "gmock/internal/gmock-port.h" - -namespace testing { -namespace internal { - -// A macro from the ACTION* family (defined later in this file) -// defines an action that can be used in a mock function. Typically, -// these actions only care about a subset of the arguments of the mock -// function. For example, if such an action only uses the second -// argument, it can be used in any mock function that takes >= 2 -// arguments where the type of the second argument is compatible. -// -// Therefore, the action implementation must be prepared to take more -// arguments than it needs. The ExcessiveArg type is used to -// represent those excessive arguments. In order to keep the compiler -// error messages tractable, we define it in the testing namespace -// instead of testing::internal. However, this is an INTERNAL TYPE -// and subject to change without notice, so a user MUST NOT USE THIS -// TYPE DIRECTLY. -struct ExcessiveArg {}; - -// A helper class needed for implementing the ACTION* macros. -template -class ActionHelper { - public: -$range i 0..n -$for i - -[[ -$var template = [[$if i==0 [[]] $else [[ -$range j 0..i-1 - template <$for j, [[typename A$j]]> -]]]] -$range j 0..i-1 -$var As = [[$for j, [[A$j]]]] -$var as = [[$for j, [[std::get<$j>(args)]]]] -$range k 1..n-i -$var eas = [[$for k, [[ExcessiveArg()]]]] -$var arg_list = [[$if (i==0) | (i==n) [[$as$eas]] $else [[$as, $eas]]]] -$template - static Result Perform(Impl* impl, const ::std::tuple<$As>& args) { - return impl->template gmock_PerformImpl<$As>(args, $arg_list); - } - -]] -}; - -} // namespace internal -} // namespace testing - -// The ACTION* family of macros can be used in a namespace scope to -// define custom actions easily. The syntax: -// -// ACTION(name) { statements; } -// -// will define an action with the given name that executes the -// statements. The value returned by the statements will be used as -// the return value of the action. Inside the statements, you can -// refer to the K-th (0-based) argument of the mock function by -// 'argK', and refer to its type by 'argK_type'. For example: -// -// ACTION(IncrementArg1) { -// arg1_type temp = arg1; -// return ++(*temp); -// } -// -// allows you to write -// -// ...WillOnce(IncrementArg1()); -// -// You can also refer to the entire argument tuple and its type by -// 'args' and 'args_type', and refer to the mock function type and its -// return type by 'function_type' and 'return_type'. -// -// Note that you don't need to specify the types of the mock function -// arguments. However rest assured that your code is still type-safe: -// you'll get a compiler error if *arg1 doesn't support the ++ -// operator, or if the type of ++(*arg1) isn't compatible with the -// mock function's return type, for example. -// -// Sometimes you'll want to parameterize the action. For that you can use -// another macro: -// -// ACTION_P(name, param_name) { statements; } -// -// For example: -// -// ACTION_P(Add, n) { return arg0 + n; } -// -// will allow you to write: -// -// ...WillOnce(Add(5)); -// -// Note that you don't need to provide the type of the parameter -// either. If you need to reference the type of a parameter named -// 'foo', you can write 'foo_type'. For example, in the body of -// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type -// of 'n'. -// -// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P$n to support -// multi-parameter actions. -// -// For the purpose of typing, you can view -// -// ACTION_Pk(Foo, p1, ..., pk) { ... } -// -// as shorthand for -// -// template -// FooActionPk Foo(p1_type p1, ..., pk_type pk) { ... } -// -// In particular, you can provide the template type arguments -// explicitly when invoking Foo(), as in Foo(5, false); -// although usually you can rely on the compiler to infer the types -// for you automatically. You can assign the result of expression -// Foo(p1, ..., pk) to a variable of type FooActionPk. This can be useful when composing actions. -// -// You can also overload actions with different numbers of parameters: -// -// ACTION_P(Plus, a) { ... } -// ACTION_P2(Plus, a, b) { ... } -// -// While it's tempting to always use the ACTION* macros when defining -// a new action, you should also consider implementing ActionInterface -// or using MakePolymorphicAction() instead, especially if you need to -// use the action a lot. While these approaches require more work, -// they give you more control on the types of the mock function -// arguments and the action parameters, which in general leads to -// better compiler error messages that pay off in the long run. They -// also allow overloading actions based on parameter types (as opposed -// to just based on the number of parameters). -// -// CAVEAT: -// -// ACTION*() can only be used in a namespace scope. The reason is -// that C++ doesn't yet allow function-local types to be used to -// instantiate templates. The up-coming C++0x standard will fix this. -// Once that's done, we'll consider supporting using ACTION*() inside -// a function. -// -// MORE INFORMATION: -// -// To learn more about using these macros, please search for 'ACTION' on -// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md - -$range i 0..n -$range k 0..n-1 - -// An internal macro needed for implementing ACTION*(). -#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\ - const args_type& args GTEST_ATTRIBUTE_UNUSED_ -$for k [[, \ - const arg$k[[]]_type& arg$k GTEST_ATTRIBUTE_UNUSED_]] - - -// Sometimes you want to give an action explicit template parameters -// that cannot be inferred from its value parameters. ACTION() and -// ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that -// and can be viewed as an extension to ACTION() and ACTION_P*(). -// -// The syntax: -// -// ACTION_TEMPLATE(ActionName, -// HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), -// AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } -// -// defines an action template that takes m explicit template -// parameters and n value parameters. name_i is the name of the i-th -// template parameter, and kind_i specifies whether it's a typename, -// an integral constant, or a template. p_i is the name of the i-th -// value parameter. -// -// Example: -// -// // DuplicateArg(output) converts the k-th argument of the mock -// // function to type T and copies it to *output. -// ACTION_TEMPLATE(DuplicateArg, -// HAS_2_TEMPLATE_PARAMS(int, k, typename, T), -// AND_1_VALUE_PARAMS(output)) { -// *output = T(::std::get(args)); -// } -// ... -// int n; -// EXPECT_CALL(mock, Foo(_, _)) -// .WillOnce(DuplicateArg<1, unsigned char>(&n)); -// -// To create an instance of an action template, write: -// -// ActionName(v1, ..., v_n) -// -// where the ts are the template arguments and the vs are the value -// arguments. The value argument types are inferred by the compiler. -// If you want to explicitly specify the value argument types, you can -// provide additional template arguments: -// -// ActionName(v1, ..., v_n) -// -// where u_i is the desired type of v_i. -// -// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the -// number of value parameters, but not on the number of template -// parameters. Without the restriction, the meaning of the following -// is unclear: -// -// OverloadedAction(x); -// -// Are we using a single-template-parameter action where 'bool' refers -// to the type of x, or are we using a two-template-parameter action -// where the compiler is asked to infer the type of x? -// -// Implementation notes: -// -// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and -// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for -// implementing ACTION_TEMPLATE. The main trick we use is to create -// new macro invocations when expanding a macro. For example, we have -// -// #define ACTION_TEMPLATE(name, template_params, value_params) -// ... GMOCK_INTERNAL_DECL_##template_params ... -// -// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...) -// to expand to -// -// ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ... -// -// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the -// preprocessor will continue to expand it to -// -// ... typename T ... -// -// This technique conforms to the C++ standard and is portable. It -// allows us to implement action templates using O(N) code, where N is -// the maximum number of template/value parameters supported. Without -// using it, we'd have to devote O(N^2) amount of code to implement all -// combinations of m and n. - -// Declares the template parameters. - -$range j 1..n -$for j [[ -$range m 0..j-1 -#define GMOCK_INTERNAL_DECL_HAS_$j[[]] -_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[kind$m name$m]] - - -]] - -// Lists the template parameters. - -$for j [[ -$range m 0..j-1 -#define GMOCK_INTERNAL_LIST_HAS_$j[[]] -_TEMPLATE_PARAMS($for m, [[kind$m, name$m]]) $for m, [[name$m]] - - -]] - -// Declares the types of value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_DECL_TYPE_AND_$i[[]] -_VALUE_PARAMS($for j, [[p$j]]) $for j [[, typename p$j##_type]] - - -]] - -// Initializes the value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_INIT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])\ - ($for j, [[p$j##_type gmock_p$j]])$if i>0 [[ : ]]$for j, [[p$j(::std::move(gmock_p$j))]] - - -]] - -// Declares the fields for storing the value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_DEFN_AND_$i[[]] -_VALUE_PARAMS($for j, [[p$j]]) $for j [[p$j##_type p$j; ]] - - -]] - -// Lists the value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_LIST_AND_$i[[]] -_VALUE_PARAMS($for j, [[p$j]]) $for j, [[p$j]] - - -]] - -// Lists the value parameter types. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_LIST_TYPE_AND_$i[[]] -_VALUE_PARAMS($for j, [[p$j]]) $for j [[, p$j##_type]] - - -]] - -// Declares the value parameters. - -$for i [[ -$range j 0..i-1 -#define GMOCK_INTERNAL_DECL_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]] -$for j, [[p$j##_type p$j]] - - -]] - -// The suffix of the class template implementing the action template. -$for i [[ - - -$range j 0..i-1 -#define GMOCK_INTERNAL_COUNT_AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]]) [[]] -$if i==1 [[P]] $elif i>=2 [[P$i]] -]] - - -// The name of the class template implementing the action template. -#define GMOCK_ACTION_CLASS_(name, value_params)\ - GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) - -$range k 0..n-1 - -#define ACTION_TEMPLATE(name, template_params, value_params)\ - template \ - class GMOCK_ACTION_CLASS_(name, value_params) {\ - public:\ - explicit GMOCK_ACTION_CLASS_(name, value_params)\ - GMOCK_INTERNAL_INIT_##value_params {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template <$for k, [[typename arg$k[[]]_type]]>\ - return_type gmock_PerformImpl(const args_type& args[[]] -$for k [[, const arg$k[[]]_type& arg$k]]) const;\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(\ - new gmock_Impl(GMOCK_INTERNAL_LIST_##value_params));\ - }\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\ - };\ - template \ - inline GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\ - GMOCK_INTERNAL_DECL_##value_params) {\ - return GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>(\ - GMOCK_INTERNAL_LIST_##value_params);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::\ - gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -$for i - -[[ -$var template = [[$if i==0 [[]] $else [[ -$range j 0..i-1 - - template <$for j, [[typename p$j##_type]]>\ -]]]] -$var class_name = [[name##Action[[$if i==0 [[]] $elif i==1 [[P]] - $else [[P$i]]]]]] -$range j 0..i-1 -$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]] -$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]] -$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::forward(gmock_p$j))]]]]]] -$var param_field_decls = [[$for j -[[ - - p$j##_type p$j;\ -]]]] -$var param_field_decls2 = [[$for j -[[ - - p$j##_type p$j;\ -]]]] -$var params = [[$for j, [[p$j]]]] -$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]] -$var typename_arg_types = [[$for k, [[typename arg$k[[]]_type]]]] -$var arg_types_and_names = [[$for k, [[const arg$k[[]]_type& arg$k]]]] -$var macro_name = [[$if i==0 [[ACTION]] $elif i==1 [[ACTION_P]] - $else [[ACTION_P$i]]]] - -#define $macro_name(name$for j [[, p$j]])\$template - class $class_name {\ - public:\ - [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - [[$if i==1 [[explicit ]]]]gmock_Impl($ctor_param_list)$inits {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template <$typename_arg_types>\ - return_type gmock_PerformImpl(const args_type& args, [[]] -$arg_types_and_names) const;\$param_field_decls - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl($params));\ - }\$param_field_decls2 - private:\ - GTEST_DISALLOW_ASSIGN_($class_name);\ - };\$template - inline $class_name$param_types name($param_types_and_names) {\ - return $class_name$param_types($params);\ - }\$template - template \ - template <$typename_arg_types>\ - typename ::testing::internal::Function::Result\ - $class_name$param_types::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const -]] -$$ } // This meta comment fixes auto-indentation in Emacs. It won't -$$ // show up in the generated code. - - -namespace testing { - - -// The ACTION*() macros trigger warning C4100 (unreferenced formal -// parameter) in MSVC with -W4. Unfortunately they cannot be fixed in -// the macro definition, as the warnings are generated when the macro -// is expanded and macro expansion cannot contain #pragma. Therefore -// we suppress them here. -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) -#endif - -// Various overloads for InvokeArgument(). -// -// The InvokeArgument(a1, a2, ..., a_k) action invokes the N-th -// (0-based) argument, which must be a k-ary callable, of the mock -// function, with arguments a1, a2, ..., a_k. -// -// Notes: -// -// 1. The arguments are passed by value by default. If you need to -// pass an argument by reference, wrap it inside ByRef(). For -// example, -// -// InvokeArgument<1>(5, string("Hello"), ByRef(foo)) -// -// passes 5 and string("Hello") by value, and passes foo by -// reference. -// -// 2. If the callable takes an argument by reference but ByRef() is -// not used, it will receive the reference to a copy of the value, -// instead of the original value. For example, when the 0-th -// argument of the mock function takes a const string&, the action -// -// InvokeArgument<0>(string("Hello")) -// -// makes a copy of the temporary string("Hello") object and passes a -// reference of the copy, instead of the original temporary object, -// to the callable. This makes it easy for a user to define an -// InvokeArgument action from temporary values and have it performed -// later. - -namespace internal { -namespace invoke_argument { - -// Appears in InvokeArgumentAdl's argument list to help avoid -// accidental calls to user functions of the same name. -struct AdlTag {}; - -// InvokeArgumentAdl - a helper for InvokeArgument. -// The basic overloads are provided here for generic functors. -// Overloads for other custom-callables are provided in the -// internal/custom/callback-actions.h header. - -$range i 0..n -$for i -[[ -$range j 1..i - -template -R InvokeArgumentAdl(AdlTag, F f[[$for j [[, A$j a$j]]]]) { - return f([[$for j, [[a$j]]]]); -} -]] - -} // namespace invoke_argument -} // namespace internal - -$range i 0..n -$for i [[ -$range j 0..i-1 - -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_$i[[]]_VALUE_PARAMS($for j, [[p$j]])) { - using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::std::get(args)$for j [[, p$j]]); -} - -]] - -// Various overloads for ReturnNew(). -// -// The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new -// instance of type T, constructed on the heap with constructor arguments -// a1, a2, ..., and a_k. The caller assumes ownership of the returned value. -$range i 0..n -$for i [[ -$range j 0..i-1 -$var ps = [[$for j, [[p$j]]]] - -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_$i[[]]_VALUE_PARAMS($ps)) { - return new T($ps); -} - -]] - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -} // namespace testing - -// Include any custom callback actions added by the local installation. -// We must include this header at the end to make sure it can use the -// declarations from this file. -#include "gmock/internal/custom/gmock-generated-actions.h" - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h deleted file mode 100644 index cd9578178c0..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h +++ /dev/null @@ -1,752 +0,0 @@ -// This file was GENERATED by command: -// pump.py gmock-generated-function-mockers.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements function mockers of various arities. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ - -#include -#include - -#include "gmock/gmock-spec-builders.h" -#include "gmock/internal/gmock-internal-utils.h" - -namespace testing { -namespace internal { -// Removes the given pointer; this is a helper for the expectation setter method -// for parameterless matchers. -// -// We want to make sure that the user cannot set a parameterless expectation on -// overloaded methods, including methods which are overloaded on const. Example: -// -// class MockClass { -// MOCK_METHOD0(GetName, string&()); -// MOCK_CONST_METHOD0(GetName, const string&()); -// }; -// -// TEST() { -// // This should be an error, as it's not clear which overload is expected. -// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value)); -// } -// -// Here are the generated expectation-setter methods: -// -// class MockClass { -// // Overload 1 -// MockSpec gmock_GetName() { ... } -// // Overload 2. Declared const so that the compiler will generate an -// // error when trying to resolve between this and overload 4 in -// // 'gmock_GetName(WithoutMatchers(), nullptr)'. -// MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { -// // Removes const from this, calls overload 1 -// return AdjustConstness_(this)->gmock_GetName(); -// } -// -// // Overload 3 -// const string& gmock_GetName() const { ... } -// // Overload 4 -// MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { -// // Does not remove const, calls overload 3 -// return AdjustConstness_const(this)->gmock_GetName(); -// } -// } -// -template -const MockType* AdjustConstness_const(const MockType* mock) { - return mock; -} - -// Removes const from and returns the given pointer; this is a helper for the -// expectation setter method for parameterless matchers. -template -MockType* AdjustConstness_(const MockType* mock) { - return const_cast(mock); -} - -} // namespace internal - -// The style guide prohibits "using" statements in a namespace scope -// inside a header file. However, the FunctionMocker class template -// is meant to be defined in the ::testing namespace. The following -// line is just a trick for working around a bug in MSVC 8.0, which -// cannot handle it if we define FunctionMocker in ::testing. -using internal::FunctionMocker; - -// GMOCK_RESULT_(tn, F) expands to the result type of function type F. -// We define this as a variadic macro in case F contains unprotected -// commas (the same reason that we use variadic macros in other places -// in this file). -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_RESULT_(tn, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::Result - -// The type of argument N of the given function type. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_ARG_(tn, N, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::template Arg::type - -// The matcher type for argument N of the given function type. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MATCHER_(tn, N, ...) \ - const ::testing::Matcher& - -// The variable for mocking the given method. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MOCKER_(arity, constness, Method) \ - GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \ - static_assert(0 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - ) constness { \ - GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(0, constness, Method).Invoke(); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method() constness { \ - GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(0, constness, Method).With(); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \ - static_assert(1 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ - GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(1, constness, \ - Method).Invoke(::std::forward(gmock_a1)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ - GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \ - static_assert(2 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2) constness { \ - GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(2, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ - GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \ - static_assert(3 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, \ - __VA_ARGS__) gmock_a3) constness { \ - GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(3, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ - GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \ - static_assert(4 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ - GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(4, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ - GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \ - static_assert(5 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5) constness { \ - GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(5, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ - GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \ - static_assert(6 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, \ - __VA_ARGS__) gmock_a6) constness { \ - GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(6, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ - GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \ - static_assert(7 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ - GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(7, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6), \ - ::std::forward(gmock_a7)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ - GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \ - static_assert(8 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \ - __VA_ARGS__) gmock_a8) constness { \ - GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(8, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6), \ - ::std::forward(gmock_a7), \ - ::std::forward(gmock_a8)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ - GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \ - static_assert(9 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \ - __VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, \ - __VA_ARGS__) gmock_a9) constness { \ - GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(9, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6), \ - ::std::forward(gmock_a7), \ - ::std::forward(gmock_a8), \ - ::std::forward(gmock_a9)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ - GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ - gmock_a9); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \ - Method) - -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \ - static_assert(10 == \ - ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, \ - "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, \ - __VA_ARGS__) gmock_a2, GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, GMOCK_ARG_(tn, 5, \ - __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, \ - __VA_ARGS__) gmock_a8, GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \ - GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \ - GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(10, constness, \ - Method).Invoke(::std::forward(gmock_a1), \ - ::std::forward(gmock_a2), \ - ::std::forward(gmock_a3), \ - ::std::forward(gmock_a4), \ - ::std::forward(gmock_a5), \ - ::std::forward(gmock_a6), \ - ::std::forward(gmock_a7), \ - ::std::forward(gmock_a8), \ - ::std::forward(gmock_a9), \ - ::std::forward(gmock_a10)); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \ - GMOCK_MATCHER_(tn, 10, \ - __VA_ARGS__) gmock_a10) constness { \ - GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ - gmock_a10); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method(::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A(), \ - ::testing::A()); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \ - Method) - -#define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__) -#define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__) -#define MOCK_METHOD2(m, ...) GMOCK_METHOD2_(, , , m, __VA_ARGS__) -#define MOCK_METHOD3(m, ...) GMOCK_METHOD3_(, , , m, __VA_ARGS__) -#define MOCK_METHOD4(m, ...) GMOCK_METHOD4_(, , , m, __VA_ARGS__) -#define MOCK_METHOD5(m, ...) GMOCK_METHOD5_(, , , m, __VA_ARGS__) -#define MOCK_METHOD6(m, ...) GMOCK_METHOD6_(, , , m, __VA_ARGS__) -#define MOCK_METHOD7(m, ...) GMOCK_METHOD7_(, , , m, __VA_ARGS__) -#define MOCK_METHOD8(m, ...) GMOCK_METHOD8_(, , , m, __VA_ARGS__) -#define MOCK_METHOD9(m, ...) GMOCK_METHOD9_(, , , m, __VA_ARGS__) -#define MOCK_METHOD10(m, ...) GMOCK_METHOD10_(, , , m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0(m, ...) GMOCK_METHOD0_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD1(m, ...) GMOCK_METHOD1_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD2(m, ...) GMOCK_METHOD2_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD3(m, ...) GMOCK_METHOD3_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD4(m, ...) GMOCK_METHOD4_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD5(m, ...) GMOCK_METHOD5_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD6(m, ...) GMOCK_METHOD6_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD7(m, ...) GMOCK_METHOD7_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD8(m, ...) GMOCK_METHOD8_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD9(m, ...) GMOCK_METHOD9_(, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD10(m, ...) GMOCK_METHOD10_(, const, , m, __VA_ARGS__) - -#define MOCK_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__) -#define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0_T(m, ...) \ - GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD1_T(m, ...) \ - GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD2_T(m, ...) \ - GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD3_T(m, ...) \ - GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD4_T(m, ...) \ - GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD5_T(m, ...) \ - GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD6_T(m, ...) \ - GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD7_T(m, ...) \ - GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD8_T(m, ...) \ - GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD9_T(m, ...) \ - GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD10_T(m, ...) \ - GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__) - -#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(, , ct, m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__) - -#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__) - -} // namespace testing - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h.pump b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h.pump deleted file mode 100644 index a56e132f348..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h.pump +++ /dev/null @@ -1,227 +0,0 @@ -$$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert -$$ it to gmock-generated-function-mockers.h. -$$ -$var n = 10 $$ The maximum arity we support. -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements function mockers of various arities. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ - -#include -#include - -#include "gmock/gmock-spec-builders.h" -#include "gmock/internal/gmock-internal-utils.h" - -namespace testing { -namespace internal { - -$range i 0..n -// Removes the given pointer; this is a helper for the expectation setter method -// for parameterless matchers. -// -// We want to make sure that the user cannot set a parameterless expectation on -// overloaded methods, including methods which are overloaded on const. Example: -// -// class MockClass { -// MOCK_METHOD0(GetName, string&()); -// MOCK_CONST_METHOD0(GetName, const string&()); -// }; -// -// TEST() { -// // This should be an error, as it's not clear which overload is expected. -// EXPECT_CALL(mock, GetName).WillOnce(ReturnRef(value)); -// } -// -// Here are the generated expectation-setter methods: -// -// class MockClass { -// // Overload 1 -// MockSpec gmock_GetName() { ... } -// // Overload 2. Declared const so that the compiler will generate an -// // error when trying to resolve between this and overload 4 in -// // 'gmock_GetName(WithoutMatchers(), nullptr)'. -// MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { -// // Removes const from this, calls overload 1 -// return AdjustConstness_(this)->gmock_GetName(); -// } -// -// // Overload 3 -// const string& gmock_GetName() const { ... } -// // Overload 4 -// MockSpec gmock_GetName( -// const WithoutMatchers&, const Function*) const { -// // Does not remove const, calls overload 3 -// return AdjustConstness_const(this)->gmock_GetName(); -// } -// } -// -template -const MockType* AdjustConstness_const(const MockType* mock) { - return mock; -} - -// Removes const from and returns the given pointer; this is a helper for the -// expectation setter method for parameterless matchers. -template -MockType* AdjustConstness_(const MockType* mock) { - return const_cast(mock); -} - -} // namespace internal - -// The style guide prohibits "using" statements in a namespace scope -// inside a header file. However, the FunctionMocker class template -// is meant to be defined in the ::testing namespace. The following -// line is just a trick for working around a bug in MSVC 8.0, which -// cannot handle it if we define FunctionMocker in ::testing. -using internal::FunctionMocker; - -// GMOCK_RESULT_(tn, F) expands to the result type of function type F. -// We define this as a variadic macro in case F contains unprotected -// commas (the same reason that we use variadic macros in other places -// in this file). -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_RESULT_(tn, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::Result - -// The type of argument N of the given function type. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_ARG_(tn, N, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::template Arg::type - -// The matcher type for argument N of the given function type. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MATCHER_(tn, N, ...) \ - const ::testing::Matcher& - -// The variable for mocking the given method. -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MOCKER_(arity, constness, Method) \ - GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) - - -$for i [[ -$range j 1..i -$var arg_as = [[$for j, [[GMOCK_ARG_(tn, $j, __VA_ARGS__) gmock_a$j]]]] -$var as = [[$for j, \ - [[::std::forward(gmock_a$j)]]]] -$var matcher_arg_as = [[$for j, \ - [[GMOCK_MATCHER_(tn, $j, __VA_ARGS__) gmock_a$j]]]] -$var matcher_as = [[$for j, [[gmock_a$j]]]] -$var anything_matchers = [[$for j, \ - [[::testing::A()]]]] -// INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD$i[[]]_(tn, constness, ct, Method, ...) \ - static_assert($i == ::testing::internal::Function<__VA_ARGS__>::ArgumentCount, "MOCK_METHOD must match argument count.");\ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - $arg_as) constness { \ - GMOCK_MOCKER_($i, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_($i, constness, Method).Invoke($as); \ - } \ - ::testing::MockSpec<__VA_ARGS__> \ - gmock_##Method($matcher_arg_as) constness { \ - GMOCK_MOCKER_($i, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_($i, constness, Method).With($matcher_as); \ - } \ - ::testing::MockSpec<__VA_ARGS__> gmock_##Method( \ - const ::testing::internal::WithoutMatchers&, \ - constness ::testing::internal::Function<__VA_ARGS__>* ) const { \ - return ::testing::internal::AdjustConstness_##constness(this)-> \ - gmock_##Method($anything_matchers); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_($i, constness, Method) - - -]] -$for i [[ -#define MOCK_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, , , m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_CONST_METHOD$i(m, ...) GMOCK_METHOD$i[[]]_(, const, , m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_METHOD$i[[]]_T(m, ...) GMOCK_METHOD$i[[]]_(typename, , , m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_CONST_METHOD$i[[]]_T(m, ...) \ - GMOCK_METHOD$i[[]]_(typename, const, , m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD$i[[]]_(, , ct, m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_CONST_METHOD$i[[]]_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD$i[[]]_(, const, ct, m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD$i[[]]_(typename, , ct, m, __VA_ARGS__) - -]] - - -$for i [[ -#define MOCK_CONST_METHOD$i[[]]_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD$i[[]]_(typename, const, ct, m, __VA_ARGS__) - -]] - -} // namespace testing - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-matchers.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-matchers.h deleted file mode 100644 index f9c927c1dfa..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-matchers.h +++ /dev/null @@ -1,1100 +0,0 @@ -// This file was GENERATED by command: -// pump.py gmock-generated-matchers.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used variadic matchers. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ - -#include -#include -#include -#include -#include -#include "gmock/gmock-matchers.h" - -// The MATCHER* family of macros can be used in a namespace scope to -// define custom matchers easily. -// -// Basic Usage -// =========== -// -// The syntax -// -// MATCHER(name, description_string) { statements; } -// -// defines a matcher with the given name that executes the statements, -// which must return a bool to indicate if the match succeeds. Inside -// the statements, you can refer to the value being matched by 'arg', -// and refer to its type by 'arg_type'. -// -// The description string documents what the matcher does, and is used -// to generate the failure message when the match fails. Since a -// MATCHER() is usually defined in a header file shared by multiple -// C++ source files, we require the description to be a C-string -// literal to avoid possible side effects. It can be empty, in which -// case we'll use the sequence of words in the matcher name as the -// description. -// -// For example: -// -// MATCHER(IsEven, "") { return (arg % 2) == 0; } -// -// allows you to write -// -// // Expects mock_foo.Bar(n) to be called where n is even. -// EXPECT_CALL(mock_foo, Bar(IsEven())); -// -// or, -// -// // Verifies that the value of some_expression is even. -// EXPECT_THAT(some_expression, IsEven()); -// -// If the above assertion fails, it will print something like: -// -// Value of: some_expression -// Expected: is even -// Actual: 7 -// -// where the description "is even" is automatically calculated from the -// matcher name IsEven. -// -// Argument Type -// ============= -// -// Note that the type of the value being matched (arg_type) is -// determined by the context in which you use the matcher and is -// supplied to you by the compiler, so you don't need to worry about -// declaring it (nor can you). This allows the matcher to be -// polymorphic. For example, IsEven() can be used to match any type -// where the value of "(arg % 2) == 0" can be implicitly converted to -// a bool. In the "Bar(IsEven())" example above, if method Bar() -// takes an int, 'arg_type' will be int; if it takes an unsigned long, -// 'arg_type' will be unsigned long; and so on. -// -// Parameterizing Matchers -// ======================= -// -// Sometimes you'll want to parameterize the matcher. For that you -// can use another macro: -// -// MATCHER_P(name, param_name, description_string) { statements; } -// -// For example: -// -// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -// -// will allow you to write: -// -// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -// -// which may lead to this message (assuming n is 10): -// -// Value of: Blah("a") -// Expected: has absolute value 10 -// Actual: -9 -// -// Note that both the matcher description and its parameter are -// printed, making the message human-friendly. -// -// In the matcher definition body, you can write 'foo_type' to -// reference the type of a parameter named 'foo'. For example, in the -// body of MATCHER_P(HasAbsoluteValue, value) above, you can write -// 'value_type' to refer to the type of 'value'. -// -// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P10 to -// support multi-parameter matchers. -// -// Describing Parameterized Matchers -// ================================= -// -// The last argument to MATCHER*() is a string-typed expression. The -// expression can reference all of the matcher's parameters and a -// special bool-typed variable named 'negation'. When 'negation' is -// false, the expression should evaluate to the matcher's description; -// otherwise it should evaluate to the description of the negation of -// the matcher. For example, -// -// using testing::PrintToString; -// -// MATCHER_P2(InClosedRange, low, hi, -// std::string(negation ? "is not" : "is") + " in range [" + -// PrintToString(low) + ", " + PrintToString(hi) + "]") { -// return low <= arg && arg <= hi; -// } -// ... -// EXPECT_THAT(3, InClosedRange(4, 6)); -// EXPECT_THAT(3, Not(InClosedRange(2, 4))); -// -// would generate two failures that contain the text: -// -// Expected: is in range [4, 6] -// ... -// Expected: is not in range [2, 4] -// -// If you specify "" as the description, the failure message will -// contain the sequence of words in the matcher name followed by the -// parameter values printed as a tuple. For example, -// -// MATCHER_P2(InClosedRange, low, hi, "") { ... } -// ... -// EXPECT_THAT(3, InClosedRange(4, 6)); -// EXPECT_THAT(3, Not(InClosedRange(2, 4))); -// -// would generate two failures that contain the text: -// -// Expected: in closed range (4, 6) -// ... -// Expected: not (in closed range (2, 4)) -// -// Types of Matcher Parameters -// =========================== -// -// For the purpose of typing, you can view -// -// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } -// -// as shorthand for -// -// template -// FooMatcherPk -// Foo(p1_type p1, ..., pk_type pk) { ... } -// -// When you write Foo(v1, ..., vk), the compiler infers the types of -// the parameters v1, ..., and vk for you. If you are not happy with -// the result of the type inference, you can specify the types by -// explicitly instantiating the template, as in Foo(5, -// false). As said earlier, you don't get to (or need to) specify -// 'arg_type' as that's determined by the context in which the matcher -// is used. You can assign the result of expression Foo(p1, ..., pk) -// to a variable of type FooMatcherPk. This -// can be useful when composing matchers. -// -// While you can instantiate a matcher template with reference types, -// passing the parameters by pointer usually makes your code more -// readable. If, however, you still want to pass a parameter by -// reference, be aware that in the failure message generated by the -// matcher you will see the value of the referenced object but not its -// address. -// -// Explaining Match Results -// ======================== -// -// Sometimes the matcher description alone isn't enough to explain why -// the match has failed or succeeded. For example, when expecting a -// long string, it can be very helpful to also print the diff between -// the expected string and the actual one. To achieve that, you can -// optionally stream additional information to a special variable -// named result_listener, whose type is a pointer to class -// MatchResultListener: -// -// MATCHER_P(EqualsLongString, str, "") { -// if (arg == str) return true; -// -// *result_listener << "the difference: " -/// << DiffStrings(str, arg); -// return false; -// } -// -// Overloading Matchers -// ==================== -// -// You can overload matchers with different numbers of parameters: -// -// MATCHER_P(Blah, a, description_string1) { ... } -// MATCHER_P2(Blah, a, b, description_string2) { ... } -// -// Caveats -// ======= -// -// When defining a new matcher, you should also consider implementing -// MatcherInterface or using MakePolymorphicMatcher(). These -// approaches require more work than the MATCHER* macros, but also -// give you more control on the types of the value being matched and -// the matcher parameters, which may leads to better compiler error -// messages when the matcher is used wrong. They also allow -// overloading matchers based on parameter types (as opposed to just -// based on the number of parameters). -// -// MATCHER*() can only be used in a namespace scope. The reason is -// that C++ doesn't yet allow function-local types to be used to -// instantiate templates. The up-coming C++0x standard will fix this. -// Once that's done, we'll consider supporting using MATCHER*() inside -// a function. -// -// More Information -// ================ -// -// To learn more about using these macros, please search for 'MATCHER' -// on -// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md - -#define MATCHER(name, description)\ - class name##Matcher {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl()\ - {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple<>()));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl());\ - }\ - name##Matcher() {\ - }\ - private:\ - };\ - inline name##Matcher name() {\ - return name##Matcher();\ - }\ - template \ - bool name##Matcher::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P(name, p0, description)\ - template \ - class name##MatcherP {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - explicit gmock_Impl(p0##_type gmock_p0)\ - : p0(::std::move(gmock_p0)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0));\ - }\ - explicit name##MatcherP(p0##_type gmock_p0) : p0(::std::move(gmock_p0)) {\ - }\ - p0##_type const p0;\ - private:\ - };\ - template \ - inline name##MatcherP name(p0##_type p0) {\ - return name##MatcherP(p0);\ - }\ - template \ - template \ - bool name##MatcherP::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P2(name, p0, p1, description)\ - template \ - class name##MatcherP2 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1));\ - }\ - name##MatcherP2(p0##_type gmock_p0, \ - p1##_type gmock_p1) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - private:\ - };\ - template \ - inline name##MatcherP2 name(p0##_type p0, \ - p1##_type p1) {\ - return name##MatcherP2(p0, p1);\ - }\ - template \ - template \ - bool name##MatcherP2::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P3(name, p0, p1, p2, description)\ - template \ - class name##MatcherP3 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2));\ - }\ - name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - private:\ - };\ - template \ - inline name##MatcherP3 name(p0##_type p0, \ - p1##_type p1, p2##_type p2) {\ - return name##MatcherP3(p0, p1, p2);\ - }\ - template \ - template \ - bool name##MatcherP3::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P4(name, p0, p1, p2, p3, description)\ - template \ - class name##MatcherP4 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, \ - p1, p2, p3)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3));\ - }\ - name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - private:\ - };\ - template \ - inline name##MatcherP4 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3) {\ - return name##MatcherP4(p0, \ - p1, p2, p3);\ - }\ - template \ - template \ - bool name##MatcherP4::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\ - template \ - class name##MatcherP5 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4));\ - }\ - name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - private:\ - };\ - template \ - inline name##MatcherP5 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4) {\ - return name##MatcherP5(p0, p1, p2, p3, p4);\ - }\ - template \ - template \ - bool name##MatcherP5::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\ - template \ - class name##MatcherP6 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4, p5)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5));\ - }\ - name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - private:\ - };\ - template \ - inline name##MatcherP6 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3, p4##_type p4, p5##_type p5) {\ - return name##MatcherP6(p0, p1, p2, p3, p4, p5);\ - }\ - template \ - template \ - bool name##MatcherP6::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\ - template \ - class name##MatcherP7 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ - p6(::std::move(gmock_p6)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4, p5, \ - p6)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6));\ - }\ - name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - private:\ - };\ - template \ - inline name##MatcherP7 name(p0##_type p0, p1##_type p1, \ - p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6) {\ - return name##MatcherP7(p0, p1, p2, p3, p4, p5, p6);\ - }\ - template \ - template \ - bool name##MatcherP7::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\ - template \ - class name##MatcherP8 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ - p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, \ - p3, p4, p5, p6, p7)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7));\ - }\ - name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - private:\ - };\ - template \ - inline name##MatcherP8 name(p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6, p7##_type p7) {\ - return name##MatcherP8(p0, p1, p2, p3, p4, p5, \ - p6, p7);\ - }\ - template \ - template \ - bool name##MatcherP8::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\ - template \ - class name##MatcherP9 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ - p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)), \ - p8(::std::move(gmock_p8)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - p8##_type const p8;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8));\ - }\ - name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - p8##_type const p8;\ - private:\ - };\ - template \ - inline name##MatcherP9 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ - p8##_type p8) {\ - return name##MatcherP9(p0, p1, p2, \ - p3, p4, p5, p6, p7, p8);\ - }\ - template \ - template \ - bool name##MatcherP9::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\ - template \ - class name##MatcherP10 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9)\ - : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1)), \ - p2(::std::move(gmock_p2)), p3(::std::move(gmock_p3)), \ - p4(::std::move(gmock_p4)), p5(::std::move(gmock_p5)), \ - p6(::std::move(gmock_p6)), p7(::std::move(gmock_p7)), \ - p8(::std::move(gmock_p8)), p9(::std::move(gmock_p9)) {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - p8##_type const p8;\ - p9##_type const p9;\ - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\ - }\ - name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8, p9##_type gmock_p9) : p0(::std::move(gmock_p0)), \ - p1(::std::move(gmock_p1)), p2(::std::move(gmock_p2)), \ - p3(::std::move(gmock_p3)), p4(::std::move(gmock_p4)), \ - p5(::std::move(gmock_p5)), p6(::std::move(gmock_p6)), \ - p7(::std::move(gmock_p7)), p8(::std::move(gmock_p8)), \ - p9(::std::move(gmock_p9)) {\ - }\ - p0##_type const p0;\ - p1##_type const p1;\ - p2##_type const p2;\ - p3##_type const p3;\ - p4##_type const p4;\ - p5##_type const p5;\ - p6##_type const p6;\ - p7##_type const p7;\ - p8##_type const p8;\ - p9##_type const p9;\ - private:\ - };\ - template \ - inline name##MatcherP10 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9) {\ - return name##MatcherP10(p0, \ - p1, p2, p3, p4, p5, p6, p7, p8, p9);\ - }\ - template \ - template \ - bool name##MatcherP10::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-matchers.h.pump b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-matchers.h.pump deleted file mode 100644 index 43a0c5fa416..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-generated-matchers.h.pump +++ /dev/null @@ -1,349 +0,0 @@ -$$ -*- mode: c++; -*- -$$ This is a Pump source file. Please use Pump to convert -$$ it to gmock-generated-matchers.h. -$$ -$var n = 10 $$ The maximum arity we support. -$$ }} This line fixes auto-indentation of the following code in Emacs. -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used variadic matchers. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ - -#include -#include -#include -#include -#include -#include "gmock/gmock-matchers.h" - -// The MATCHER* family of macros can be used in a namespace scope to -// define custom matchers easily. -// -// Basic Usage -// =========== -// -// The syntax -// -// MATCHER(name, description_string) { statements; } -// -// defines a matcher with the given name that executes the statements, -// which must return a bool to indicate if the match succeeds. Inside -// the statements, you can refer to the value being matched by 'arg', -// and refer to its type by 'arg_type'. -// -// The description string documents what the matcher does, and is used -// to generate the failure message when the match fails. Since a -// MATCHER() is usually defined in a header file shared by multiple -// C++ source files, we require the description to be a C-string -// literal to avoid possible side effects. It can be empty, in which -// case we'll use the sequence of words in the matcher name as the -// description. -// -// For example: -// -// MATCHER(IsEven, "") { return (arg % 2) == 0; } -// -// allows you to write -// -// // Expects mock_foo.Bar(n) to be called where n is even. -// EXPECT_CALL(mock_foo, Bar(IsEven())); -// -// or, -// -// // Verifies that the value of some_expression is even. -// EXPECT_THAT(some_expression, IsEven()); -// -// If the above assertion fails, it will print something like: -// -// Value of: some_expression -// Expected: is even -// Actual: 7 -// -// where the description "is even" is automatically calculated from the -// matcher name IsEven. -// -// Argument Type -// ============= -// -// Note that the type of the value being matched (arg_type) is -// determined by the context in which you use the matcher and is -// supplied to you by the compiler, so you don't need to worry about -// declaring it (nor can you). This allows the matcher to be -// polymorphic. For example, IsEven() can be used to match any type -// where the value of "(arg % 2) == 0" can be implicitly converted to -// a bool. In the "Bar(IsEven())" example above, if method Bar() -// takes an int, 'arg_type' will be int; if it takes an unsigned long, -// 'arg_type' will be unsigned long; and so on. -// -// Parameterizing Matchers -// ======================= -// -// Sometimes you'll want to parameterize the matcher. For that you -// can use another macro: -// -// MATCHER_P(name, param_name, description_string) { statements; } -// -// For example: -// -// MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } -// -// will allow you to write: -// -// EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); -// -// which may lead to this message (assuming n is 10): -// -// Value of: Blah("a") -// Expected: has absolute value 10 -// Actual: -9 -// -// Note that both the matcher description and its parameter are -// printed, making the message human-friendly. -// -// In the matcher definition body, you can write 'foo_type' to -// reference the type of a parameter named 'foo'. For example, in the -// body of MATCHER_P(HasAbsoluteValue, value) above, you can write -// 'value_type' to refer to the type of 'value'. -// -// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to -// support multi-parameter matchers. -// -// Describing Parameterized Matchers -// ================================= -// -// The last argument to MATCHER*() is a string-typed expression. The -// expression can reference all of the matcher's parameters and a -// special bool-typed variable named 'negation'. When 'negation' is -// false, the expression should evaluate to the matcher's description; -// otherwise it should evaluate to the description of the negation of -// the matcher. For example, -// -// using testing::PrintToString; -// -// MATCHER_P2(InClosedRange, low, hi, -// std::string(negation ? "is not" : "is") + " in range [" + -// PrintToString(low) + ", " + PrintToString(hi) + "]") { -// return low <= arg && arg <= hi; -// } -// ... -// EXPECT_THAT(3, InClosedRange(4, 6)); -// EXPECT_THAT(3, Not(InClosedRange(2, 4))); -// -// would generate two failures that contain the text: -// -// Expected: is in range [4, 6] -// ... -// Expected: is not in range [2, 4] -// -// If you specify "" as the description, the failure message will -// contain the sequence of words in the matcher name followed by the -// parameter values printed as a tuple. For example, -// -// MATCHER_P2(InClosedRange, low, hi, "") { ... } -// ... -// EXPECT_THAT(3, InClosedRange(4, 6)); -// EXPECT_THAT(3, Not(InClosedRange(2, 4))); -// -// would generate two failures that contain the text: -// -// Expected: in closed range (4, 6) -// ... -// Expected: not (in closed range (2, 4)) -// -// Types of Matcher Parameters -// =========================== -// -// For the purpose of typing, you can view -// -// MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } -// -// as shorthand for -// -// template -// FooMatcherPk -// Foo(p1_type p1, ..., pk_type pk) { ... } -// -// When you write Foo(v1, ..., vk), the compiler infers the types of -// the parameters v1, ..., and vk for you. If you are not happy with -// the result of the type inference, you can specify the types by -// explicitly instantiating the template, as in Foo(5, -// false). As said earlier, you don't get to (or need to) specify -// 'arg_type' as that's determined by the context in which the matcher -// is used. You can assign the result of expression Foo(p1, ..., pk) -// to a variable of type FooMatcherPk. This -// can be useful when composing matchers. -// -// While you can instantiate a matcher template with reference types, -// passing the parameters by pointer usually makes your code more -// readable. If, however, you still want to pass a parameter by -// reference, be aware that in the failure message generated by the -// matcher you will see the value of the referenced object but not its -// address. -// -// Explaining Match Results -// ======================== -// -// Sometimes the matcher description alone isn't enough to explain why -// the match has failed or succeeded. For example, when expecting a -// long string, it can be very helpful to also print the diff between -// the expected string and the actual one. To achieve that, you can -// optionally stream additional information to a special variable -// named result_listener, whose type is a pointer to class -// MatchResultListener: -// -// MATCHER_P(EqualsLongString, str, "") { -// if (arg == str) return true; -// -// *result_listener << "the difference: " -/// << DiffStrings(str, arg); -// return false; -// } -// -// Overloading Matchers -// ==================== -// -// You can overload matchers with different numbers of parameters: -// -// MATCHER_P(Blah, a, description_string1) { ... } -// MATCHER_P2(Blah, a, b, description_string2) { ... } -// -// Caveats -// ======= -// -// When defining a new matcher, you should also consider implementing -// MatcherInterface or using MakePolymorphicMatcher(). These -// approaches require more work than the MATCHER* macros, but also -// give you more control on the types of the value being matched and -// the matcher parameters, which may leads to better compiler error -// messages when the matcher is used wrong. They also allow -// overloading matchers based on parameter types (as opposed to just -// based on the number of parameters). -// -// MATCHER*() can only be used in a namespace scope. The reason is -// that C++ doesn't yet allow function-local types to be used to -// instantiate templates. The up-coming C++0x standard will fix this. -// Once that's done, we'll consider supporting using MATCHER*() inside -// a function. -// -// More Information -// ================ -// -// To learn more about using these macros, please search for 'MATCHER' -// on -// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md - -$range i 0..n -$for i - -[[ -$var macro_name = [[$if i==0 [[MATCHER]] $elif i==1 [[MATCHER_P]] - $else [[MATCHER_P$i]]]] -$var class_name = [[name##Matcher[[$if i==0 [[]] $elif i==1 [[P]] - $else [[P$i]]]]]] -$range j 0..i-1 -$var template = [[$if i==0 [[]] $else [[ - - template <$for j, [[typename p$j##_type]]>\ -]]]] -$var ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]] -$var impl_ctor_param_list = [[$for j, [[p$j##_type gmock_p$j]]]] -$var impl_inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]] -$var inits = [[$if i==0 [[]] $else [[ : $for j, [[p$j(::std::move(gmock_p$j))]]]]]] -$var params = [[$for j, [[p$j]]]] -$var param_types = [[$if i==0 [[]] $else [[<$for j, [[p$j##_type]]>]]]] -$var param_types_and_names = [[$for j, [[p$j##_type p$j]]]] -$var param_field_decls = [[$for j -[[ - - p$j##_type const p$j;\ -]]]] -$var param_field_decls2 = [[$for j -[[ - - p$j##_type const p$j;\ -]]]] - -#define $macro_name(name$for j [[, p$j]], description)\$template - class $class_name {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface<\ - GTEST_REFERENCE_TO_CONST_(arg_type)> {\ - public:\ - [[$if i==1 [[explicit ]]]]gmock_Impl($impl_ctor_param_list)\ - $impl_inits {}\ - virtual bool MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\$param_field_decls - private:\ - ::std::string FormatDescription(bool negation) const {\ - ::std::string gmock_description = (description);\ - if (!gmock_description.empty()) {\ - return gmock_description;\ - }\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::std::tuple<$for j, [[p$j##_type]]>($for j, [[p$j]])));\ - }\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl($params));\ - }\ - [[$if i==1 [[explicit ]]]]$class_name($ctor_param_list)$inits {\ - }\$param_field_decls2 - private:\ - };\$template - inline $class_name$param_types name($param_types_and_names) {\ - return $class_name$param_types($params);\ - }\$template - template \ - bool $class_name$param_types::gmock_Impl::MatchAndExplain(\ - GTEST_REFERENCE_TO_CONST_(arg_type) arg,\ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const -]] - - -#endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-matchers.h b/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-matchers.h deleted file mode 100644 index fcf8cf26e1b..00000000000 --- a/submodules/ton/tonlib-src/third-party/crc32c/third_party/googletest/googlemock/include/gmock/gmock-matchers.h +++ /dev/null @@ -1,4570 +0,0 @@ -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Mock - a framework for writing C++ mock classes. -// -// This file implements some commonly used argument matchers. More -// matchers can be defined by the user implementing the -// MatcherInterface interface if necessary. -// -// See googletest/include/gtest/gtest-matchers.h for the definition of class -// Matcher, class MatcherInterface, and others. - -// GOOGLETEST_CM0002 DO NOT DELETE - -#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ -#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ - -#include -#include -#include -#include -#include -#include -#include // NOLINT -#include -#include -#include -#include -#include -#include "gmock/internal/gmock-internal-utils.h" -#include "gmock/internal/gmock-port.h" -#include "gtest/gtest.h" - -// MSVC warning C5046 is new as of VS2017 version 15.8. -#if defined(_MSC_VER) && _MSC_VER >= 1915 -#define GMOCK_MAYBE_5046_ 5046 -#else -#define GMOCK_MAYBE_5046_ -#endif - -GTEST_DISABLE_MSC_WARNINGS_PUSH_( - 4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by - clients of class B */ - /* Symbol involving type with internal linkage not defined */) - -namespace testing { - -// To implement a matcher Foo for type T, define: -// 1. a class FooMatcherImpl that implements the -// MatcherInterface interface, and -// 2. a factory function that creates a Matcher object from a -// FooMatcherImpl*. -// -// The two-level delegation design makes it possible to allow a user -// to write "v" instead of "Eq(v)" where a Matcher is expected, which -// is impossible if we pass matchers by pointers. It also eases -// ownership management as Matcher objects can now be copied like -// plain values. - -// A match result listener that stores the explanation in a string. -class StringMatchResultListener : public MatchResultListener { - public: - StringMatchResultListener() : MatchResultListener(&ss_) {} - - // Returns the explanation accumulated so far. - std::string str() const { return ss_.str(); } - - // Clears the explanation accumulated so far. - void Clear() { ss_.str(""); } - - private: - ::std::stringstream ss_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener); -}; - -// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION -// and MUST NOT BE USED IN USER CODE!!! -namespace internal { - -// The MatcherCastImpl class template is a helper for implementing -// MatcherCast(). We need this helper in order to partially -// specialize the implementation of MatcherCast() (C++ allows -// class/struct templates to be partially specialized, but not -// function templates.). - -// This general version is used when MatcherCast()'s argument is a -// polymorphic matcher (i.e. something that can be converted to a -// Matcher but is not one yet; for example, Eq(value)) or a value (for -// example, "hello"). -template -class MatcherCastImpl { - public: - static Matcher Cast(const M& polymorphic_matcher_or_value) { - // M can be a polymorphic matcher, in which case we want to use - // its conversion operator to create Matcher. Or it can be a value - // that should be passed to the Matcher's constructor. - // - // We can't call Matcher(polymorphic_matcher_or_value) when M is a - // polymorphic matcher because it'll be ambiguous if T has an implicit - // constructor from M (this usually happens when T has an implicit - // constructor from any type). - // - // It won't work to unconditionally implict_cast - // polymorphic_matcher_or_value to Matcher because it won't trigger - // a user-defined conversion from M to T if one exists (assuming M is - // a value). - return CastImpl( - polymorphic_matcher_or_value, - BooleanConstant< - std::is_convertible >::value>(), - BooleanConstant< - std::is_convertible::value>()); - } - - private: - template - static Matcher CastImpl(const M& polymorphic_matcher_or_value, - BooleanConstant /* convertible_to_matcher */, - BooleanConstant) { - // M is implicitly convertible to Matcher, which means that either - // M is a polymorphic matcher or Matcher has an implicit constructor - // from M. In both cases using the implicit conversion will produce a - // matcher. - // - // Even if T has an implicit constructor from M, it won't be called because - // creating Matcher would require a chain of two user-defined conversions - // (first to create T from M and then to create Matcher from T). - return polymorphic_matcher_or_value; - } - - // M can't be implicitly converted to Matcher, so M isn't a polymorphic - // matcher. It's a value of a type implicitly convertible to T. Use direct - // initialization to create a matcher. - static Matcher CastImpl( - const M& value, BooleanConstant /* convertible_to_matcher */, - BooleanConstant /* convertible_to_T */) { - return Matcher(ImplicitCast_(value)); - } - - // M can't be implicitly converted to either Matcher or T. Attempt to use - // polymorphic matcher Eq(value) in this case. - // - // Note that we first attempt to perform an implicit cast on the value and - // only fall back to the polymorphic Eq() matcher afterwards because the - // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end - // which might be undefined even when Rhs is implicitly convertible to Lhs - // (e.g. std::pair vs. std::pair). - // - // We don't define this method inline as we need the declaration of Eq(). - static Matcher CastImpl( - const M& value, BooleanConstant /* convertible_to_matcher */, - BooleanConstant /* convertible_to_T */); -}; - -// This more specialized version is used when MatcherCast()'s argument -// is already a Matcher. This only compiles when type T can be -// statically converted to type U. -template -class MatcherCastImpl > { - public: - static Matcher Cast(const Matcher& source_matcher) { - return Matcher(new Impl(source_matcher)); - } - - private: - class Impl : public MatcherInterface { - public: - explicit Impl(const Matcher& source_matcher) - : source_matcher_(source_matcher) {} - - // We delegate the matching logic to the source matcher. - bool MatchAndExplain(T x, MatchResultListener* listener) const override { - using FromType = typename std::remove_cv::type>::type>::type; - using ToType = typename std::remove_cv::type>::type>::type; - // Do not allow implicitly converting base*/& to derived*/&. - static_assert( - // Do not trigger if only one of them is a pointer. That implies a - // regular conversion and not a down_cast. - (std::is_pointer::type>::value != - std::is_pointer::type>::value) || - std::is_same::value || - !std::is_base_of::value, - "Can't implicitly convert from to "); - - return source_matcher_.MatchAndExplain(static_cast(x), listener); - } - - void DescribeTo(::std::ostream* os) const override { - source_matcher_.DescribeTo(os); - } - - void DescribeNegationTo(::std::ostream* os) const override { - source_matcher_.DescribeNegationTo(os); - } - - private: - const Matcher source_matcher_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; -}; - -// This even more specialized version is used for efficiently casting -// a matcher to its own type. -template -class MatcherCastImpl > { - public: - static Matcher Cast(const Matcher& matcher) { return matcher; } -}; - -} // namespace internal - -// In order to be safe and clear, casting between different matcher -// types is done explicitly via MatcherCast(m), which takes a -// matcher m and returns a Matcher. It compiles only when T can be -// statically converted to the argument type of m. -template -inline Matcher MatcherCast(const M& matcher) { - return internal::MatcherCastImpl::Cast(matcher); -} - -// Implements SafeMatcherCast(). -// -// FIXME: The intermediate SafeMatcherCastImpl class was introduced as a -// workaround for a compiler bug, and can now be removed. -template -class SafeMatcherCastImpl { - public: - // This overload handles polymorphic matchers and values only since - // monomorphic matchers are handled by the next one. - template - static inline Matcher Cast(const M& polymorphic_matcher_or_value) { - return internal::MatcherCastImpl::Cast(polymorphic_matcher_or_value); - } - - // This overload handles monomorphic matchers. - // - // In general, if type T can be implicitly converted to type U, we can - // safely convert a Matcher to a Matcher (i.e. Matcher is - // contravariant): just keep a copy of the original Matcher, convert the - // argument from type T to U, and then pass it to the underlying Matcher. - // The only exception is when U is a reference and T is not, as the - // underlying Matcher may be interested in the argument's address, which - // is not preserved in the conversion from T to U. - template - static inline Matcher Cast(const Matcher& matcher) { - // Enforce that T can be implicitly converted to U. - GTEST_COMPILE_ASSERT_((std::is_convertible::value), - "T must be implicitly convertible to U"); - // Enforce that we are not converting a non-reference type T to a reference - // type U. - GTEST_COMPILE_ASSERT_( - internal::is_reference::value || !internal::is_reference::value, - cannot_convert_non_reference_arg_to_reference); - // In case both T and U are arithmetic types, enforce that the - // conversion is not lossy. - typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; - typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; - const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; - const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; - GTEST_COMPILE_ASSERT_( - kTIsOther || kUIsOther || - (internal::LosslessArithmeticConvertible::value), - conversion_of_arithmetic_types_must_be_lossless); - return MatcherCast(matcher); - } -}; - -template -inline Matcher SafeMatcherCast(const M& polymorphic_matcher) { - return SafeMatcherCastImpl::Cast(polymorphic_matcher); -} - -// A() returns a matcher that matches any value of type T. -template -Matcher A(); - -// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION -// and MUST NOT BE USED IN USER CODE!!! -namespace internal { - -// If the explanation is not empty, prints it to the ostream. -inline void PrintIfNotEmpty(const std::string& explanation, - ::std::ostream* os) { - if (explanation != "" && os != nullptr) { - *os << ", " << explanation; - } -} - -// Returns true if the given type name is easy to read by a human. -// This is used to decide whether printing the type of a value might -// be helpful. -inline bool IsReadableTypeName(const std::string& type_name) { - // We consider a type name readable if it's short or doesn't contain - // a template or function type. - return (type_name.length() <= 20 || - type_name.find_first_of("<(") == std::string::npos); -} - -// Matches the value against the given matcher, prints the value and explains -// the match result to the listener. Returns the match result. -// 'listener' must not be NULL. -// Value cannot be passed by const reference, because some matchers take a -// non-const argument. -template -bool MatchPrintAndExplain(Value& value, const Matcher& matcher, - MatchResultListener* listener) { - if (!listener->IsInterested()) { - // If the listener is not interested, we do not need to construct the - // inner explanation. - return matcher.Matches(value); - } - - StringMatchResultListener inner_listener; - const bool match = matcher.MatchAndExplain(value, &inner_listener); - - UniversalPrint(value, listener->stream()); -#if GTEST_HAS_RTTI - const std::string& type_name = GetTypeName(); - if (IsReadableTypeName(type_name)) - *listener->stream() << " (of type " << type_name << ")"; -#endif - PrintIfNotEmpty(inner_listener.str(), listener->stream()); - - return match; -} - -// An internal helper class for doing compile-time loop on a tuple's -// fields. -template -class TuplePrefix { - public: - // TuplePrefix::Matches(matcher_tuple, value_tuple) returns true - // iff the first N fields of matcher_tuple matches the first N - // fields of value_tuple, respectively. - template - static bool Matches(const MatcherTuple& matcher_tuple, - const ValueTuple& value_tuple) { - return TuplePrefix::Matches(matcher_tuple, value_tuple) && - std::get(matcher_tuple).Matches(std::get(value_tuple)); - } - - // TuplePrefix::ExplainMatchFailuresTo(matchers, values, os) - // describes failures in matching the first N fields of matchers - // against the first N fields of values. If there is no failure, - // nothing will be streamed to os. - template - static void ExplainMatchFailuresTo(const MatcherTuple& matchers, - const ValueTuple& values, - ::std::ostream* os) { - // First, describes failures in the first N - 1 fields. - TuplePrefix::ExplainMatchFailuresTo(matchers, values, os); - - // Then describes the failure (if any) in the (N - 1)-th (0-based) - // field. - typename std::tuple_element::type matcher = - std::get(matchers); - typedef typename std::tuple_element::type Value; - const Value& value = std::get(values); - StringMatchResultListener listener; - if (!matcher.MatchAndExplain(value, &listener)) { - *os << " Expected arg #" << N - 1 << ": "; - std::get(matchers).DescribeTo(os); - *os << "\n Actual: "; - // We remove the reference in type Value to prevent the - // universal printer from printing the address of value, which - // isn't interesting to the user most of the time. The - // matcher's MatchAndExplain() method handles the case when - // the address is interesting. - internal::UniversalPrint(value, os); - PrintIfNotEmpty(listener.str(), os); - *os << "\n"; - } - } -}; - -// The base case. -template <> -class TuplePrefix<0> { - public: - template - static bool Matches(const MatcherTuple& /* matcher_tuple */, - const ValueTuple& /* value_tuple */) { - return true; - } - - template - static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */, - const ValueTuple& /* values */, - ::std::ostream* /* os */) {} -}; - -// TupleMatches(matcher_tuple, value_tuple) returns true iff all -// matchers in matcher_tuple match the corresponding fields in -// value_tuple. It is a compiler error if matcher_tuple and -// value_tuple have different number of fields or incompatible field -// types. -template -bool TupleMatches(const MatcherTuple& matcher_tuple, - const ValueTuple& value_tuple) { - // Makes sure that matcher_tuple and value_tuple have the same - // number of fields. - GTEST_COMPILE_ASSERT_(std::tuple_size::value == - std::tuple_size::value, - matcher_and_value_have_different_numbers_of_fields); - return TuplePrefix::value>::Matches(matcher_tuple, - value_tuple); -} - -// Describes failures in matching matchers against values. If there -// is no failure, nothing will be streamed to os. -template -void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, - const ValueTuple& values, - ::std::ostream* os) { - TuplePrefix::value>::ExplainMatchFailuresTo( - matchers, values, os); -} - -// TransformTupleValues and its helper. -// -// TransformTupleValuesHelper hides the internal machinery that -// TransformTupleValues uses to implement a tuple traversal. -template -class TransformTupleValuesHelper { - private: - typedef ::std::tuple_size TupleSize; - - public: - // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'. - // Returns the final value of 'out' in case the caller needs it. - static OutIter Run(Func f, const Tuple& t, OutIter out) { - return IterateOverTuple()(f, t, out); - } - - private: - template - struct IterateOverTuple { - OutIter operator() (Func f, const Tup& t, OutIter out) const { - *out++ = f(::std::get(t)); - return IterateOverTuple()(f, t, out); - } - }; - template - struct IterateOverTuple { - OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const { - return out; - } - }; -}; - -// Successively invokes 'f(element)' on each element of the tuple 't', -// appending each result to the 'out' iterator. Returns the final value -// of 'out'. -template -OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { - return TransformTupleValuesHelper::Run(f, t, out); -} - -// Implements A(). -template -class AnyMatcherImpl : public MatcherInterface { - public: - bool MatchAndExplain(const T& /* x */, - MatchResultListener* /* listener */) const override { - return true; - } - void DescribeTo(::std::ostream* os) const override { *os << "is anything"; } - void DescribeNegationTo(::std::ostream* os) const override { - // This is mostly for completeness' safe, as it's not very useful - // to write Not(A()). However we cannot completely rule out - // such a possibility, and it doesn't hurt to be prepared. - *os << "never matches"; - } -}; - -// Implements _, a matcher that matches any value of any -// type. This is a polymorphic matcher, so we need a template type -// conversion operator to make it appearing as a Matcher for any -// type T. -class AnythingMatcher { - public: - template - operator Matcher() const { return A(); } -}; - -// Implements the polymorphic IsNull() matcher, which matches any raw or smart -// pointer that is NULL. -class IsNullMatcher { - public: - template - bool MatchAndExplain(const Pointer& p, - MatchResultListener* /* listener */) const { - return p == nullptr; - } - - void DescribeTo(::std::ostream* os) const { *os << "is NULL"; } - void DescribeNegationTo(::std::ostream* os) const { - *os << "isn't NULL"; - } -}; - -// Implements the polymorphic NotNull() matcher, which matches any raw or smart -// pointer that is not NULL. -class NotNullMatcher { - public: - template - bool MatchAndExplain(const Pointer& p, - MatchResultListener* /* listener */) const { - return p != nullptr; - } - - void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; } - void DescribeNegationTo(::std::ostream* os) const { - *os << "is NULL"; - } -}; - -// Ref(variable) matches any argument that is a reference to -// 'variable'. This matcher is polymorphic as it can match any -// super type of the type of 'variable'. -// -// The RefMatcher template class implements Ref(variable). It can -// only be instantiated with a reference type. This prevents a user -// from mistakenly using Ref(x) to match a non-reference function -// argument. For example, the following will righteously cause a -// compiler error: -// -// int n; -// Matcher m1 = Ref(n); // This won't compile. -// Matcher m2 = Ref(n); // This will compile. -template -class RefMatcher; - -template -class RefMatcher { - // Google Mock is a generic framework and thus needs to support - // mocking any function types, including those that take non-const - // reference arguments. Therefore the template parameter T (and - // Super below) can be instantiated to either a const type or a - // non-const type. - public: - // RefMatcher() takes a T& instead of const T&, as we want the - // compiler to catch using Ref(const_value) as a matcher for a - // non-const reference. - explicit RefMatcher(T& x) : object_(x) {} // NOLINT - - template - operator Matcher() const { - // By passing object_ (type T&) to Impl(), which expects a Super&, - // we make sure that Super is a super type of T. In particular, - // this catches using Ref(const_value) as a matcher for a - // non-const reference, as you cannot implicitly convert a const - // reference to a non-const reference. - return MakeMatcher(new Impl(object_)); - } - - private: - template - class Impl : public MatcherInterface { - public: - explicit Impl(Super& x) : object_(x) {} // NOLINT - - // MatchAndExplain() takes a Super& (as opposed to const Super&) - // in order to match the interface MatcherInterface. - bool MatchAndExplain(Super& x, - MatchResultListener* listener) const override { - *listener << "which is located @" << static_cast(&x); - return &x == &object_; - } - - void DescribeTo(::std::ostream* os) const override { - *os << "references the variable "; - UniversalPrinter::Print(object_, os); - } - - void DescribeNegationTo(::std::ostream* os) const override { - *os << "does not reference the variable "; - UniversalPrinter::Print(object_, os); - } - - private: - const Super& object_; - - GTEST_DISALLOW_ASSIGN_(Impl); - }; - - T& object_; - - GTEST_DISALLOW_ASSIGN_(RefMatcher); -}; - -// Polymorphic helper functions for narrow and wide string matchers. -inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { - return String::CaseInsensitiveCStringEquals(lhs, rhs); -} - -inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs, - const wchar_t* rhs) { - return String::CaseInsensitiveWideCStringEquals(lhs, rhs); -} - -// String comparison for narrow or wide strings that can have embedded NUL -// characters. -template -bool CaseInsensitiveStringEquals(const StringType& s1, - const StringType& s2) { - // Are the heads equal? - if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) { - return false; - } - - // Skip the equal heads. - const typename StringType::value_type nul = 0; - const size_t i1 = s1.find(nul), i2 = s2.find(nul); - - // Are we at the end of either s1 or s2? - if (i1 == StringType::npos || i2 == StringType::npos) { - return i1 == i2; - } - - // Are the tails equal? - return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1)); -} - -// String matchers. - -// Implements equality-based string matchers like StrEq, StrCaseNe, and etc. -template -class StrEqualityMatcher { - public: - StrEqualityMatcher(const StringType& str, bool expect_eq, - bool case_sensitive) - : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} - -#if GTEST_HAS_ABSL - bool MatchAndExplain(const absl::string_view& s, - MatchResultListener* listener) const { - // This should fail to compile if absl::string_view is used with wide - // strings. - const StringType& str = std::string(s); - return MatchAndExplain(str, listener); - } -#endif // GTEST_HAS_ABSL - - // Accepts pointer types, particularly: - // const char* - // char* - // const wchar_t* - // wchar_t* - template - bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - if (s == nullptr) { - return !expect_eq_; - } - return MatchAndExplain(StringType(s), listener); - } - - // Matches anything that can convert to StringType. - // - // This is a template, not just a plain function with const StringType&, - // because absl::string_view has some interfering non-explicit constructors. - template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { - const StringType& s2(s); - const bool eq = case_sensitive_ ? s2 == string_ : - CaseInsensitiveStringEquals(s2, string_); - return expect_eq_ == eq; - } - - void DescribeTo(::std::ostream* os) const { - DescribeToHelper(expect_eq_, os); - } - - void DescribeNegationTo(::std::ostream* os) const { - DescribeToHelper(!expect_eq_, os); - } - - private: - void DescribeToHelper(bool expect_eq, ::std::ostream* os) const { - *os << (expect_eq ? "is " : "isn't "); - *os << "equal to "; - if (!case_sensitive_) { - *os << "(ignoring case) "; - } - UniversalPrint(string_, os); - } - - const StringType string_; - const bool expect_eq_; - const bool case_sensitive_; - - GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher); -}; - -// Implements the polymorphic HasSubstr(substring) matcher, which -// can be used as a Matcher as long as T can be converted to a -// string. -template -class HasSubstrMatcher { - public: - explicit HasSubstrMatcher(const StringType& substring) - : substring_(substring) {} - -#if GTEST_HAS_ABSL - bool MatchAndExplain(const absl::string_view& s, - MatchResultListener* listener) const { - // This should fail to compile if absl::string_view is used with wide - // strings. - const StringType& str = std::string(s); - return MatchAndExplain(str, listener); - } -#endif // GTEST_HAS_ABSL - - // Accepts pointer types, particularly: - // const char* - // char* - // const wchar_t* - // wchar_t* - template - bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - return s != nullptr && MatchAndExplain(StringType(s), listener); - } - - // Matches anything that can convert to StringType. - // - // This is a template, not just a plain function with const StringType&, - // because absl::string_view has some interfering non-explicit constructors. - template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { - const StringType& s2(s); - return s2.find(substring_) != StringType::npos; - } - - // Describes what this matcher matches. - void DescribeTo(::std::ostream* os) const { - *os << "has substring "; - UniversalPrint(substring_, os); - } - - void DescribeNegationTo(::std::ostream* os) const { - *os << "has no substring "; - UniversalPrint(substring_, os); - } - - private: - const StringType substring_; - - GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher); -}; - -// Implements the polymorphic StartsWith(substring) matcher, which -// can be used as a Matcher as long as T can be converted to a -// string. -template -class StartsWithMatcher { - public: - explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { - } - -#if GTEST_HAS_ABSL - bool MatchAndExplain(const absl::string_view& s, - MatchResultListener* listener) const { - // This should fail to compile if absl::string_view is used with wide - // strings. - const StringType& str = std::string(s); - return MatchAndExplain(str, listener); - } -#endif // GTEST_HAS_ABSL - - // Accepts pointer types, particularly: - // const char* - // char* - // const wchar_t* - // wchar_t* - template - bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - return s != nullptr && MatchAndExplain(StringType(s), listener); - } - - // Matches anything that can convert to StringType. - // - // This is a template, not just a plain function with const StringType&, - // because absl::string_view has some interfering non-explicit constructors. - template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { - const StringType& s2(s); - return s2.length() >= prefix_.length() && - s2.substr(0, prefix_.length()) == prefix_; - } - - void DescribeTo(::std::ostream* os) const { - *os << "starts with "; - UniversalPrint(prefix_, os); - } - - void DescribeNegationTo(::std::ostream* os) const { - *os << "doesn't start with "; - UniversalPrint(prefix_, os); - } - - private: - const StringType prefix_; - - GTEST_DISALLOW_ASSIGN_(StartsWithMatcher); -}; - -// Implements the polymorphic EndsWith(substring) matcher, which -// can be used as a Matcher as long as T can be converted to a -// string. -template -class EndsWithMatcher { - public: - explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} - -#if GTEST_HAS_ABSL - bool MatchAndExplain(const absl::string_view& s, - MatchResultListener* listener) const { - // This should fail to compile if absl::string_view is used with wide - // strings. - const StringType& str = std::string(s); - return MatchAndExplain(str, listener); - } -#endif // GTEST_HAS_ABSL - - // Accepts pointer types, particularly: - // const char* - // char* - // const wchar_t* - // wchar_t* - template - bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - return s != nullptr && MatchAndExplain(StringType(s), listener); - } - - // Matches anything that can convert to StringType. - // - // This is a template, not just a plain function with const StringType&, - // because absl::string_view has some interfering non-explicit constructors. - template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { - const StringType& s2(s); - return s2.length() >= suffix_.length() && - s2.substr(s2.length() - suffix_.length()) == suffix_; - } - - void DescribeTo(::std::ostream* os) const { - *os << "ends with "; - UniversalPrint(suffix_, os); - } - - void DescribeNegationTo(::std::ostream* os) const { - *os << "doesn't end with "; - UniversalPrint(suffix_, os); - } - - private: - const StringType suffix_; - - GTEST_DISALLOW_ASSIGN_(EndsWithMatcher); -}; - -// Implements a matcher that compares the two fields of a 2-tuple -// using one of the ==, <=, <, etc, operators. The two fields being -// compared don't have to have the same type. -// -// The matcher defined here is polymorphic (for example, Eq() can be -// used to match a std::tuple, a std::tuple, -// etc). Therefore we use a template type conversion operator in the -// implementation. -template -class PairMatchBase { - public: - template - operator Matcher<::std::tuple>() const { - return Matcher<::std::tuple>(new Impl&>); - } - template - operator Matcher&>() const { - return MakeMatcher(new Impl&>); - } - - private: - static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT - return os << D::Desc(); - } - - template - class Impl : public MatcherInterface { - public: - bool MatchAndExplain(Tuple args, - MatchResultListener* /* listener */) const override { - return Op()(::std::get<0>(args), ::std::get<1>(args)); - } - void DescribeTo(::std::ostream* os) const override { - *os << "are " << GetDesc; - } - void DescribeNegationTo(::std::ostream* os) const override { - *os << "aren't " << GetDesc; - } - }; -}; - -class Eq2Matcher : public PairMatchBase { - public: - static const char* Desc() { return "an equal pair"; } -}; -class Ne2Matcher : public PairMatchBase { - public: - static const char* Desc() { return "an unequal pair"; } -}; -class Lt2Matcher : public PairMatchBase { - public: - static const char* Desc() { return "a pair where the first < the second"; } -}; -class Gt2Matcher : public PairMatchBase { - public: - static const char* Desc() { return "a pair where the first > the second"; } -}; -class Le2Matcher : public PairMatchBase { - public: - static const char* Desc() { return "a pair where the first <= the second"; } -}; -class Ge2Matcher : public PairMatchBase { - public: - static const char* Desc() { return "a pair where the first >= the second"; } -}; - -// Implements the Not(...) matcher for a particular argument type T. -// We do not nest it inside the NotMatcher class template, as that -// will prevent different instantiations of NotMatcher from sharing -// the same NotMatcherImpl class. -template -class NotMatcherImpl : public MatcherInterface { - public: - explicit NotMatcherImpl(const Matcher& matcher) - : matcher_(matcher) {} - - bool MatchAndExplain(const T& x, - MatchResultListener* listener) const override { - return !matcher_.MatchAndExplain(x, listener); - } - - void DescribeTo(::std::ostream* os) const override { - matcher_.DescribeNegationTo(os); - } - - void DescribeNegationTo(::std::ostream* os) const override { - matcher_.DescribeTo(os); - } - - private: - const Matcher matcher_; - - GTEST_DISALLOW_ASSIGN_(NotMatcherImpl); -}; - -// Implements the Not(m) matcher, which matches a value that doesn't -// match matcher m. -template -class NotMatcher { - public: - explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {} - - // This template type conversion operator allows Not(m) to be used - // to match any type m can match. - template - operator Matcher() const { - return Matcher(new NotMatcherImpl(SafeMatcherCast(matcher_))); - } - - private: - InnerMatcher matcher_; - - GTEST_DISALLOW_ASSIGN_(NotMatcher); -}; - -// Implements the AllOf(m1, m2) matcher for a particular argument type -// T. We do not nest it inside the BothOfMatcher class template, as -// that will prevent different instantiations of BothOfMatcher from -// sharing the same BothOfMatcherImpl class. -template -class AllOfMatcherImpl : public MatcherInterface { - public: - explicit AllOfMatcherImpl(std::vector > matchers) - : matchers_(std::move(matchers)) {} - - void DescribeTo(::std::ostream* os) const override { - *os << "("; - for (size_t i = 0; i < matchers_.size(); ++i) { - if (i != 0) *os << ") and ("; - matchers_[i].DescribeTo(os); - } - *os << ")"; - } - - void DescribeNegationTo(::std::ostream* os) const override { - *os << "("; - for (size_t i = 0; i < matchers_.size(); ++i) { - if (i != 0) *os << ") or ("; - matchers_[i].DescribeNegationTo(os); - } - *os << ")"; - } - - bool MatchAndExplain(const T& x, - MatchResultListener* listener) const override { - // If either matcher1_ or matcher2_ doesn't match x, we only need - // to explain why one of them fails. - std::string all_match_result; - - for (size_t i = 0; i < matchers_.size(); ++i) { - StringMatchResultListener slistener; - if (matchers_[i].MatchAndExplain(x, &slistener)) { - if (all_match_result.empty()) { - all_match_result = slistener.str(); - } else { - std::string result = slistener.str(); - if (!result.empty()) { - all_match_result += ", and "; - all_match_result += result; - } - } - } else { - *listener << slistener.str(); - return false; - } - } - - // Otherwise we need to explain why *both* of them match. - *listener << all_match_result; - return true; - } - - private: - const std::vector > matchers_; - - GTEST_DISALLOW_ASSIGN_(AllOfMatcherImpl); -}; - -// VariadicMatcher is used for the variadic implementation of -// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...). -// CombiningMatcher is used to recursively combine the provided matchers -// (of type Args...). -template

Introduction