Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

465 lines
18 KiB

  1. //====== Copyright � 1996-2004, Valve Corporation, All rights reserved. =======
  2. //
  3. // Purpose:
  4. //
  5. //=============================================================================
  6. #include "stdafx.h"
  7. #include <limits.h>
  8. #include "msgprotobuf.h"
  9. #include "tier0/memdbgoff.h"
  10. #ifdef GC
  11. namespace GCSDK
  12. {
  13. IMPLEMENT_CLASS_MEMPOOL( CProtoBufNetPacket, 1000, UTLMEMORYPOOL_GROW_SLOW );
  14. }
  15. #endif
  16. // memdbgon must be the last include file in a .cpp file!!!
  17. #include "tier0/memdbgon.h"
  18. namespace GCSDK
  19. {
  20. // Global pool for protobuf header allocations
  21. CProtoBufMsgMemoryPoolMgr *GProtoBufMsgMemoryPoolMgr()
  22. {
  23. static CProtoBufMsgMemoryPoolMgr s_ProtoBufMsgMemoryPoolMgr;
  24. return &s_ProtoBufMsgMemoryPoolMgr;
  25. }
  26. CThreadMutex CProtoBufMsgBase::s_PoolRegMutex;
  27. //-----------------------------------------------------------------------------
  28. // Purpose: Constructor
  29. //-----------------------------------------------------------------------------
  30. CProtoBufNetPacket::CProtoBufNetPacket( CNetPacket *pNetPacket, GCProtoBufMsgSrc eMsgSrc, const CSteamID steamID, uint32 nGCDirIndex, MsgType_t msgType )
  31. : m_msgType( msgType ), m_steamID( steamID ), m_bIsValid( false )
  32. {
  33. #ifdef VALVE_BIG_ENDIAN
  34. ProtoBufMsgHeader_t * pHdr = (ProtoBufMsgHeader_t *)pNetPacket->PubData();
  35. pHdr->m_EMsgFlagged = LittleDWord( pHdr->m_EMsgFlagged );
  36. pHdr->m_cubProtoBufExtHdr = LittleDWord( pHdr->m_cubProtoBufExtHdr );
  37. #endif
  38. m_pNetPacket = pNetPacket;
  39. m_pNetPacket->AddRef();
  40. m_pHeader = GProtoBufMsgMemoryPoolMgr()->AllocProtoBufHdr();
  41. // Pull the length of the header out of the packet, but then validate it's not longer than the packet itself (ie, corrupt packet)
  42. const uint32 unLenProtoBufHeader = GetFixedHeader().m_cubProtoBufExtHdr;
  43. if ( unLenProtoBufHeader + sizeof( ProtoBufMsgHeader_t ) <= pNetPacket->CubData() )
  44. {
  45. if ( !m_pHeader->ParseFromArray( pNetPacket->PubData()+sizeof(ProtoBufMsgHeader_t), unLenProtoBufHeader ) )
  46. {
  47. AssertMsg4( false, "Failed parsing ProtoBuf extended header out of message: %s(%d) from %s size=%u", PchMsgNameFromEMsg( GetEMsg() ), GetEMsg(), steamID.Render(), pNetPacket->CubData() );
  48. }
  49. else
  50. {
  51. //if this packet doesn't have a source provided, we need to set the source of this message. If one is already provided, we should never stomp that data as that is the ultimate source of the message
  52. if( m_pHeader->gc_msg_src() == GCProtoBufMsgSrc_Unspecified )
  53. {
  54. //make sure to set the steam ID to what steam provided so clients can't spoof it
  55. m_pHeader->set_client_steam_id( steamID.ConvertToUint64() );
  56. //and track our original source type and which GC it was first received by
  57. m_pHeader->set_gc_dir_index_source( nGCDirIndex );
  58. m_pHeader->set_gc_msg_src( eMsgSrc );
  59. }
  60. m_bIsValid = true;
  61. }
  62. }
  63. else
  64. {
  65. AssertMsg4( false, "Unparseable protobuf message arrived: message %s(%u) from %s size=%u", PchMsgNameFromEMsg( GetEMsg() ), GetEMsg(), steamID.Render(), pNetPacket->CubData() );
  66. }
  67. }
  68. //-----------------------------------------------------------------------------
  69. // Purpose: Destructor
  70. //-----------------------------------------------------------------------------
  71. CProtoBufNetPacket::~CProtoBufNetPacket()
  72. {
  73. GProtoBufMsgMemoryPoolMgr()->FreeProtoBufHdr( m_pHeader );
  74. m_pNetPacket->Release();
  75. }
  76. //-----------------------------------------------------------------------------
  77. // Purpose: Gets the body from the associated packet
  78. //-----------------------------------------------------------------------------
  79. bool CProtoBufNetPacket::GetMsgBody( const uint8*& pubData, uint32& cubData ) const
  80. {
  81. if ( !IsValid() )
  82. {
  83. pubData = NULL;
  84. cubData = 0;
  85. return false;
  86. }
  87. //when it initializes, it verifies the size, so we don't need to do validation here
  88. const uint32 nHdrOffset = sizeof( ProtoBufMsgHeader_t ) + GetFixedHeader().m_cubProtoBufExtHdr;
  89. pubData = PubData() + nHdrOffset;
  90. cubData = CubData() - nHdrOffset;
  91. return true;
  92. }
  93. //-----------------------------------------------------------------------------
  94. // Purpose: Constructor
  95. //-----------------------------------------------------------------------------
  96. CProtoBufMsgMemoryPoolBase::CProtoBufMsgMemoryPoolBase( uint32 unTargetLow, uint32 unTargetHigh )
  97. {
  98. m_unTargetCountLow = unTargetLow;
  99. m_unTargetCountHigh = unTargetHigh;
  100. m_unAllocHitCounter = 0;
  101. m_unAllocMissCounter = 0;
  102. m_unAllocated = 0;
  103. m_pTSQueueFreeObjects = new CTSQueue< ::google::protobuf::Message * >();
  104. }
  105. //-----------------------------------------------------------------------------
  106. // Purpose: Destructor
  107. //-----------------------------------------------------------------------------
  108. CProtoBufMsgMemoryPoolBase::~CProtoBufMsgMemoryPoolBase()
  109. {
  110. AssertMsg( 0 == m_pTSQueueFreeObjects->Count(), "CProtoBufMsgMemoryPoolBase destructor called with items still in the queue. They must be freed by the derived class or they will be leaked" );
  111. m_pTSQueueFreeObjects->Purge();
  112. delete m_pTSQueueFreeObjects;
  113. }
  114. //-----------------------------------------------------------------------------
  115. // Purpose: Allocs a message from the pool
  116. //-----------------------------------------------------------------------------
  117. ::google::protobuf::Message *CProtoBufMsgMemoryPoolBase::Alloc()
  118. {
  119. ::google::protobuf::Message *pObject;
  120. if ( !m_pTSQueueFreeObjects->PopItem( &pObject ) || !pObject )
  121. {
  122. ++m_unAllocMissCounter;
  123. pObject = InternalAlloc();
  124. }
  125. else
  126. {
  127. ++m_unAllocHitCounter;
  128. uint32 unCount = m_pTSQueueFreeObjects->Count();
  129. // We'll free an extra cached msg every alloc if we are over the higher limit, and every 6th if we
  130. // are over the lower limit. This allows some elasticity to peaks in demand.
  131. bool bFreeAnother = ( unCount > m_unTargetCountHigh )
  132. || ( unCount > m_unTargetCountLow && m_unAllocHitCounter % 6 == 0 );
  133. if ( bFreeAnother )
  134. {
  135. // Pop an extra item, so we can get down to target count over time
  136. ::google::protobuf::Message *pThrowAway;
  137. if ( m_pTSQueueFreeObjects->PopItem( &pThrowAway ) && pThrowAway )
  138. {
  139. InternalFree( pThrowAway );
  140. }
  141. }
  142. }
  143. ++m_unAllocated;
  144. return pObject;
  145. }
  146. //-----------------------------------------------------------------------------
  147. // Purpose: Returns a message to the pool
  148. //-----------------------------------------------------------------------------
  149. void CProtoBufMsgMemoryPoolBase::Free( ::google::protobuf::Message *pObject )
  150. {
  151. // We always cache for re-use on free, though we may throw out later on alloc to shrink the pool
  152. pObject->Clear();
  153. --m_unAllocated;
  154. m_pTSQueueFreeObjects->PushItem( pObject );
  155. }
  156. //-----------------------------------------------------------------------------
  157. // Purpose: Counts the size of all the objects in the pool
  158. //-----------------------------------------------------------------------------
  159. uint32 CProtoBufMsgMemoryPoolBase::GetEstimatedSize()
  160. {
  161. // to fix a linux build break
  162. typedef ::google::protobuf::Message ProtoMsg_t;
  163. CUtlVector<ProtoMsg_t *> vecTemp;
  164. vecTemp.EnsureCapacity( m_pTSQueueFreeObjects->Count() * 2 );
  165. // Should be "while (pObject != NULL)" because if we were actually using threads depending on count
  166. // would be bad. Unfortunately that gives me an infinite loop. See if this can be changed when this
  167. // is updated
  168. while ( m_pTSQueueFreeObjects->Count() > 0 )
  169. {
  170. ::google::protobuf::Message *pObject = NULL;
  171. m_pTSQueueFreeObjects->PopItem( &pObject );
  172. vecTemp.AddToTail( pObject );
  173. }
  174. uint32 unEstimate = 0;
  175. FOR_EACH_VEC( vecTemp, i )
  176. {
  177. unEstimate += vecTemp[i]->SpaceUsed();
  178. m_pTSQueueFreeObjects->PushItem( vecTemp[i] );
  179. }
  180. // Scale the estimate by the number of objects outstanding
  181. float fScale = 1.0f;
  182. if ( vecTemp.Count() > 0 )
  183. {
  184. float fFree = (float)vecTemp.Count();
  185. fScale = ( fFree + (float)m_unAllocated ) / fFree;
  186. unEstimate *= fScale;
  187. }
  188. return unEstimate;
  189. }
  190. //-----------------------------------------------------------------------------
  191. // Purpose: Pops an item from the queue. To be used by the derived class
  192. // destructor to free the oustanding allocations
  193. //-----------------------------------------------------------------------------
  194. bool CProtoBufMsgMemoryPoolBase::PopItem( google::protobuf::Message **ppMsg )
  195. {
  196. return m_pTSQueueFreeObjects->PopItem( ppMsg );
  197. }
  198. //-----------------------------------------------------------------------------
  199. // Purpose: Constructor
  200. //-----------------------------------------------------------------------------
  201. CProtoBufMsgMemoryPoolMgr::CProtoBufMsgMemoryPoolMgr() : m_PoolHeaders()
  202. {
  203. m_vecMsgPools.AddToTail( &m_PoolHeaders );
  204. }
  205. //-----------------------------------------------------------------------------
  206. // Purpose: Destructor
  207. //-----------------------------------------------------------------------------
  208. CProtoBufMsgMemoryPoolMgr::~CProtoBufMsgMemoryPoolMgr()
  209. {
  210. FOR_EACH_VEC( m_vecMsgPools, i )
  211. {
  212. if ( m_vecMsgPools[i] != &m_PoolHeaders )
  213. delete m_vecMsgPools[i];
  214. }
  215. }
  216. //-----------------------------------------------------------------------------
  217. // Purpose: Takes control of a message pool registered for a specific protobuf type
  218. //-----------------------------------------------------------------------------
  219. void CProtoBufMsgMemoryPoolMgr::RegisterPool( CProtoBufMsgMemoryPoolBase *pPool )
  220. {
  221. m_vecMsgPools.AddToTail( pPool );
  222. }
  223. //-----------------------------------------------------------------------------
  224. // Purpose: Prints info on protobuf memory usage
  225. //-----------------------------------------------------------------------------
  226. void CProtoBufMsgMemoryPoolMgr::DumpPoolInfo()
  227. {
  228. uint32 unTotalSize = 0;
  229. Msg( "CProtoBufMsgMemoryPoolMgr:\n" );
  230. Msg( " PoolName Allocated Free Est. Size Hit Rate\n" );
  231. Msg( " ----------------------------------------- ----------- ----------- ----------- -----------\n" );
  232. FOR_EACH_VEC( m_vecMsgPools, i )
  233. {
  234. uint32 unHitCount = m_vecMsgPools[i]->GetAllocHitCount();
  235. uint32 unMissCount = m_vecMsgPools[i]->GetAllocMissCount();
  236. float flHitRate = 0.0f;
  237. if ( unHitCount > 0 || unMissCount > 0 )
  238. {
  239. flHitRate = (float)unHitCount / (float)(unHitCount+unMissCount);
  240. flHitRate *= 100.0f;
  241. }
  242. uint32 unEstimate = m_vecMsgPools[i]->GetEstimatedSize();
  243. Msg( "%43s%12d%12d%12s%12s\n", m_vecMsgPools[i]->GetName().String(), m_vecMsgPools[i]->GetAllocated(), m_vecMsgPools[i]->GetFree(), Q_pretifymem( (float)unEstimate, 2, true ), CFmtStr( "%f%%", flHitRate ).Access() );
  244. unTotalSize += unEstimate;
  245. }
  246. Msg( " -----------------------------------------------------------------------------------------\n" );
  247. Msg( " Total: %s\n", Q_pretifymem( (float)unTotalSize, 2, true ) );
  248. }
  249. //-----------------------------------------------------------------------------
  250. // Purpose: Constructor - no eMsg, so it's a receive constructor. Don't alloc
  251. // a header in this case
  252. //-----------------------------------------------------------------------------
  253. CProtoBufMsgBase::CProtoBufMsgBase()
  254. : m_pNetPacket( NULL )
  255. , m_eMsg( 0 )
  256. , m_pProtoBufHdr( NULL )
  257. {
  258. }
  259. //-----------------------------------------------------------------------------
  260. // Purpose: Constructor - Has an eMsg, so it's a send constructor. Alloc a header
  261. //-----------------------------------------------------------------------------
  262. CProtoBufMsgBase::CProtoBufMsgBase( MsgType_t eMsg )
  263. : m_pNetPacket( NULL )
  264. , m_eMsg( eMsg )
  265. , m_pProtoBufHdr( NULL )
  266. {
  267. m_pProtoBufHdr = GProtoBufMsgMemoryPoolMgr()->AllocProtoBufHdr();
  268. }
  269. //-----------------------------------------------------------------------------
  270. // Purpose: Destructor
  271. //-----------------------------------------------------------------------------
  272. CProtoBufMsgBase::~CProtoBufMsgBase()
  273. {
  274. // If we have a net packet then it allocated the header, so we don't free it ourselves
  275. // If we don't have a net packet then we still may have not allocated a header ( default constructor )
  276. if ( m_pNetPacket )
  277. {
  278. m_pNetPacket->Release();
  279. m_pNetPacket = NULL;
  280. }
  281. else if ( m_pProtoBufHdr )
  282. {
  283. GProtoBufMsgMemoryPoolMgr()->FreeProtoBufHdr( m_pProtoBufHdr );
  284. }
  285. m_pProtoBufHdr = NULL;
  286. }
  287. //-----------------------------------------------------------------------------
  288. // Purpose: Inits a message from a received net packet
  289. //-----------------------------------------------------------------------------
  290. bool CProtoBufMsgBase::InitFromPacket( IMsgNetPacket * pNetPacket )
  291. {
  292. VPROF_BUDGET( "CProtoBufMsg::InitFromPacket( IMsgNetPacket )", VPROF_BUDGETGROUP_OTHER_NETWORKING );
  293. AssertMsg( NULL == m_pProtoBufHdr, "Encountered a packet being initialized that has outstanding memory. This will leak memory, and is often caused by receiving messages using the wrong constructor which preallocates or not clearing the message between uses" );
  294. Assert( k_EMsgFormatTypeProtocolBuffer == pNetPacket->GetEMsgFormatType() );
  295. m_pNetPacket = static_cast<CProtoBufNetPacket *>( pNetPacket );
  296. m_pNetPacket->AddRef();
  297. ProtoBufMsgHeader_t &refFixedHdr = m_pNetPacket->GetFixedHeader();
  298. m_eMsg = refFixedHdr.m_EMsgFlagged;
  299. m_pProtoBufHdr = m_pNetPacket->GetProtoHeader();
  300. const uint8* pubData;
  301. uint32 cubData;
  302. if( !m_pNetPacket->GetMsgBody( pubData, cubData ) )
  303. return false;
  304. ::google::protobuf::Message *pBody = GetGenericBody();
  305. return pBody->ParseFromArray( pubData, (int)cubData );
  306. }
  307. //-----------------------------------------------------------------------------
  308. // Purpose: Sends a message using the given handler
  309. //-----------------------------------------------------------------------------
  310. bool CProtoBufMsgBase::BAsyncSend( IProtoBufSendHandler & sender ) const
  311. {
  312. return BAsyncSendProto( sender, GetEMsg(), *m_pProtoBufHdr, *GetGenericBody() );
  313. }
  314. //-----------------------------------------------------------------------------
  315. // Purpose: Sends a protobuf object out as a message
  316. //-----------------------------------------------------------------------------
  317. bool CProtoBufMsgBase::BAsyncSendProto( IProtoBufSendHandler& sender, MsgType_t eMsgType, const CMsgProtoBufHeader& hdr, const ::google::protobuf::Message& proto )
  318. {
  319. VPROF_BUDGET( "CProtoBufMsg::BAsyncSendProto", VPROF_BUDGETGROUP_OTHER_NETWORKING );
  320. // Compute message sizes and serialize out to buffer. Need to work on a more efficient
  321. // way to write these to the net without so much copying.
  322. uint32 cubBodySize = proto.ByteSize();
  323. uint32 cubTotalSize = 0;
  324. uint8* pMsgMem = AllocateMessageMemory( eMsgType, hdr, cubBodySize, &cubTotalSize );
  325. proto.SerializeWithCachedSizesToArray( pMsgMem + cubTotalSize - cubBodySize );
  326. bool bSuccess = sender.BAsyncSend( eMsgType, pMsgMem, cubTotalSize );
  327. FreeMessageMemory( pMsgMem );
  328. return bSuccess;
  329. }
  330. //-----------------------------------------------------------------------------
  331. // Purpose: Sends a message using the given handler
  332. //-----------------------------------------------------------------------------
  333. bool CProtoBufMsgBase::BAsyncSendWithPreSerializedBody( IProtoBufSendHandler & pSender, const byte *pubBody, uint32 cubBody ) const
  334. {
  335. return BAsyncSendWithPreSerializedBody( pSender, GetEMsg(), *m_pProtoBufHdr, pubBody, cubBody );
  336. }
  337. //-----------------------------------------------------------------------------
  338. //free standing version to send a protobuff given a header and pre-serialized body. Primarily used for efficient message routing
  339. //-----------------------------------------------------------------------------
  340. bool CProtoBufMsgBase::BAsyncSendWithPreSerializedBody( IProtoBufSendHandler& sender, MsgType_t eMsgType, const CMsgProtoBufHeader& hdr, const byte* pubBody, uint32 cubBody )
  341. {
  342. VPROF_BUDGET( "CProtoBufMsg::BAsyncSendWithPreSerializedBody", VPROF_BUDGETGROUP_OTHER_NETWORKING );
  343. // Compute message sizes and serialize out to buffer. Need to work on a more efficient
  344. // way to write these to the net without so much copying.
  345. uint32 cubTotalSize = 0;
  346. uint8* pMsgMem = AllocateMessageMemory( eMsgType, hdr, cubBody, &cubTotalSize );
  347. V_memcpy( pMsgMem + cubTotalSize - cubBody, pubBody, cubBody );
  348. bool bSuccess = sender.BAsyncSend( eMsgType, pMsgMem, cubTotalSize );
  349. FreeMessageMemory( pMsgMem );
  350. return bSuccess;
  351. }
  352. //-----------------------------------------------------------------------------
  353. //utility function that handles allocating a memory pool big enough for the provided header and specified body
  354. //size and writing the header into the pool. This will return a pointer to the memory, as well as the header size.
  355. //-----------------------------------------------------------------------------
  356. uint8* CProtoBufMsgBase::AllocateMessageMemory( MsgType_t eMsgType, const CMsgProtoBufHeader& hdr, uint32 cubBodySize, uint32* pCubTotalSizeOut )
  357. {
  358. uint32 cubExtHdrSize = hdr.ByteSize();
  359. uint32 cubTotalSize = sizeof( ProtoBufMsgHeader_t ) + cubExtHdrSize + cubBodySize;
  360. ProtoBufMsgHeader_t fixedHdr( eMsgType, cubExtHdrSize );
  361. uint8 *pubMsgBytes = (uint8*)g_MemPoolMsg.Alloc( cubTotalSize );
  362. // Copy over basic fixed header
  363. // We place bytes on the network in little endian to optimize for those platforms, even though network byte order is really big endian.
  364. #if defined(VALVE_BIG_ENDIAN)
  365. ProtoBufMsgHeader_t hdrByteSwapped = fixedHdr;
  366. hdrByteSwapped.m_EMsgFlagged = DWordSwap( hdrByteSwapped.m_EMsgFlagged );
  367. hdrByteSwapped.m_cubProtoBufExtHdr = DWordSwap( hdrByteSwapped.m_cubProtoBufExtHdr );
  368. Q_memcpy( pubMsgBytes, &hdrByteSwapped, sizeof( ProtoBufMsgHeader_t ) );
  369. #else
  370. Q_memcpy( pubMsgBytes, &fixedHdr, sizeof( ProtoBufMsgHeader_t ) );
  371. #endif
  372. // Serialize extended pb header, we guarantee we didn't modify the message since the last call to ByteSize above, so use the cached sizes serialize
  373. uint8 *pEnd = hdr.SerializeWithCachedSizesToArray( pubMsgBytes + sizeof( ProtoBufMsgHeader_t ) );
  374. NOTE_UNUSED( pEnd );
  375. Assert( pEnd == pubMsgBytes + sizeof( ProtoBufMsgHeader_t ) + cubExtHdrSize );
  376. if( pCubTotalSizeOut )
  377. *pCubTotalSizeOut = cubTotalSize;
  378. return pubMsgBytes;
  379. }
  380. void CProtoBufMsgBase::FreeMessageMemory( uint8* pMemory )
  381. {
  382. g_MemPoolMsg.Free( pMemory );
  383. }
  384. }